How to write from Java to the Windows Event Log?
Asked Answered
E

4

25

How can I write from Java to the Windows Event Log?

Emie answered 2/10, 2008 at 22:20 Comment(0)
M
24

EDIT (2023): See JNA https://mcmap.net/q/528507/-how-to-write-from-java-to-the-windows-event-log

Old answer

Log4J is a Java-based logging utility. The class NTEventLogAppender can be used to "append to the NT event log system". See the documentation here:

http://logging.apache.org/log4j/1.2/apidocs/org/apache/log4j/nt/NTEventLogAppender.html

Edit: There is a newer version, Log4j 2 "that provides significant improvements over its predecessor."

Mowbray answered 2/10, 2008 at 22:27 Comment(4)
Log4J is a good choice because your code doesn't get coupled to the underlying logging target and its easily configured through XML.Baptistry
The big problem with NTEventLogAppender is that it requires a native DLL to be placed in all kinds of places you don't want it in.Wicklow
It appears to not be available in log4j2 and i don't think there's a replacement.Piny
In 2023, it appears that this answer is best (JNA): https://mcmap.net/q/528507/-how-to-write-from-java-to-the-windows-event-logMowbray
W
10

You can use JNA to write to the Event Log directly without the need of any native DLLs. See Advapi32 and Advapi32Util classes for various event log methods (ships since JNA 3.2.8).

If you're using Log4j, consider Log4jna instead of NTEventLogAppender.

Wicklow answered 28/9, 2010 at 18:10 Comment(1)
Log4jna has been moved to GITHUB, in case the link above stop working.Rooks
F
7

You can also use the eventcreate command on Windows XP Pro and above.

String command = "eventcreate "
               + " /l APPLICATION"
               + " /so \"" + applicationObjectName + "\""
               + " /t " + lvl
               + " /id " + id
               + " /d \"" + description + "\"";

Runtime.getRuntime().exec(command);

For XP home and lower, you could create a vbs application that writes using the wscript.shell.eventcreate method. However you sacrifice the ability to specify source.

Example: http://www.ozzu.com/mswindows-forum/posting-event-log-with-batch-files-t76791.html

Forequarter answered 7/2, 2010 at 4:4 Comment(1)
how to define applicationObjectName , lvl, etcJennifferjennilee
H
5

Back in 2001 JavaWorld published an article on how to write messages to the Windows NT Event Log. Or, you can take a look at the Log4j NTEventLogAppender class.

Hyaloid answered 2/10, 2008 at 22:28 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.