繁体   English   中英

如何使用 Java 和 JNA 写入 windows 事件日志

[英]How to write to windows eventlog using Java and JNA

我正在寻找一种使用 JNA 写入 windows 事件日志的方法。 我可以使用 log4J2 和 Log4JNA 库写入 windows 事件日志。

但是,我想直接使用 JNA 编写,并且我不愿意添加 Log4JNA 所需的 dll 文件。

我目前正在查看 Advapi32 和 Advapi32Util 但找不到任何写入事件日志的方法。

如何才能做到这一点?

您需要的 WINAPI 调用是ReportEvent

这映射在Advapi32中 JNA 中用户贡献的平台映射中。

Advapi32Test class 包含演示编写事件的代码 我在下面摘录了部分测试代码:

public void testReportEvent() {
    String applicationEventLog = "SYSTEM\\CurrentControlSet\\Services\\EventLog\\Application";
    String jnaEventSource = "JNADevEventSource";
    String jnaEventSourceRegistryPath = applicationEventLog + "\\" + jnaEventSource;
    // ignore test if not able to create key (need to be administrator to do this).
    try {
        final boolean keyCreated = Advapi32Util.registryCreateKey(WinReg.HKEY_LOCAL_MACHINE, jnaEventSourceRegistryPath);
        if (!keyCreated) {
            return;
        }
    } catch (Win32Exception e) {
        return;
    }

    HANDLE h = Advapi32.INSTANCE.RegisterEventSource(null, jnaEventSource);
    String s[] = {"JNA", "Event"};
    Memory m = new Memory(4);
    m.setByte(0, (byte) 1);
    m.setByte(1, (byte) 2);
    m.setByte(2, (byte) 3);
    m.setByte(3, (byte) 4);
    int eventId = 123 + 0x40000000;
    Advapi32.INSTANCE.ReportEvent(h, WinNT.EVENTLOG_ERROR_TYPE, 0, eventId, null, 2, 4, s, m);
    Advapi32Util.registryDeleteKey(WinReg.HKEY_LOCAL_MACHINE, jnaEventSourceRegistryPath);
}

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM