javawinapijnaadvapi32

How to write to windows eventlog using Java and JNA


I was looking at a way to write to windows event log using JNA. I am able to write to windows event log using log4J2 and Log4JNA libraries.

However, I would like to write directly using JNA and I am not comfortable having to add a dll file, which is required by Log4JNA.

I am currently Looking at Advapi32 and Advapi32Util but couldn't find any methods to write to event log.

How can this be done?


Solution

  • The WINAPI call you need is ReportEvent.

    This is mapped in the user-contributed platform mappings in JNA in Advapi32.

    The Advapi32Test class contains code demonstrating writing an event. I've excerpted portions of this test code below:

    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);
    }