简体   繁体   中英

Listener for Windows Event log

I could use the below java JNA code to read a windows event log

EventLogIterator iter = new EventLogIterator("EventLogName");
while(iter.hasNext()) {
    EventLogRecord record = iter.next();
    System.out.println(record.getRecordId()
            + ": Event ID: " + record.getEventId()
            + ", Event Type: " + record.getType()
            + ", Event Source: " + record.getSource());
}

I want to read/capture only new events.

Is there an option/API in JNA (or any other java library) to listen to windows event log?

EventLogIterator has two constructors, one just taking the log name and the other allowing you to specify a server and flags.

You can pass the parameter EVENTLOG_BACKWARDS_READ flag to this constructor, eg change your first line to:

new EventLogIterator(null, "EventLogName", WinNT.EVENTLOG_BACKWARDS_READ);

Since the Event Log Record Id always increases 1 , if you keep track of the previous highest value of getRecordId() then you can stop your iteration when you get to it, and only have new events.

You can easily set up this routine to poll at regular intervals.


1 The recordId's are unsigned and wrap to 0 at the max 32-bit value so the best approach for determining "new" events is to subtract the previous "highest" from the current and test for a positive number.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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