我正在研究一种使用JNA编写windows事件日志的方法。我能够使用log4J2和Log4JNA库写入windows事件日志。
但是,我想直接使用JNA编写,我不习惯添加一个Log4JNA所需的dll文件。
我目前正在查看Advapi32和Advapi32Util,但是找不到任何方法来写入事件日志。
这是如何做到的呢?
发布于 2022-01-07 16:26:57
您需要的WINAPI调用是ReportEvent。
这是在Advapi32中的JNA中用户贡献的平台映射中映射的。
Advapi32Test类包含演示编写事件的代码。我摘录了以下部分测试代码:
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);
}https://stackoverflow.com/questions/70622738
复制相似问题