November 1, 2009

Writing to Syslog with Log4J and Testing It on Ubuntu 9.04 Jaunty

The preferred way to log in Linux is to write to the Syslog. For you that comes from the Windows world, Syslog is the equivalent for the Windows NT Event Log. Before you can ran the example below you need to enable Syslog Facility LOCAL1 on Ubuntu. The Facility can be looked as a filter and if you are running multiple programs on the same server, you might want to consider to let each program write to different Facility LOCAL[0-7].

To enable Facility LOCAL1 on Ubuntu 9.04 you first need to edit /etc/syslog.conf
$ sudo gedit /etc/syslog.conf

and add the following line
local1.*   /var/log/local1.log

But we are not done yet, since Log4J org.apache.log4j.net.SyslogAppender is using the underlying writer class org.apache.log4j.helpers.SyslogWriter that is using the java.net.DatagramPacket which is writing to the syslog remotely, we need to enable remote access to Syslog. We do that by changing:
$ sudo gedit /etc/default/syslogd

And changing the following:
SYSLOGD="-r"

Now we are done and we need to restarts the system log daemon, to make our changes take affect:
$ sudo /etc/init.d/sysklogd restart

Finally we add the following configuration to our log4j.properties.
# configure the root logger
log4j.rootLogger=INFO, STDOUT, DAILY, SYSLOG_LOCAL1

# configure Syslog facility LOCAL1 appender
log4j.appender.SYSLOG_LOCAL1=org.apache.log4j.net.SyslogAppender
log4j.appender.SYSLOG_LOCAL1.threshold=WARN
log4j.appender.SYSLOG_LOCAL1.syslogHost=localhost
log4j.appender.SYSLOG_LOCAL1.facility=LOCAL1
log4j.appender.SYSLOG_LOCAL1.facilityPrinting=false
log4j.appender.SYSLOG_LOCAL1.layout=org.apache.log4j.PatternLayout
log4j.appender.SYSLOG_LOCAL1.layout.conversionPattern=[%p] %c:%L - %m%n

No comments: