Thursday, March 29, 2007

IA: Log4J, Error logging in Java

Error logging is a very important element of application development. In a previous post I've discussed the importance of error reporting in my current job. Dr. Liddle suggested we take a look at an error logging application, and suggested Log4J.

Log4J revolves around three main concepts:
  1. public class Logger- responsible for handling the majority of logging operations
  2. public interface Appender- responsible for controlling the output of the logging operations
  3. public abstract class Layout- responsible for the layout format of the output from Appender

Config files can be used in order to not have to hard code the options in your application and have to recompile it if ever you decide to change the options.

A simple configuration file in Java property format.

# The root logger is assigned priority level DEBUG and an

# appender named myAppender.

log4j.rootLogger=debug, myAppender

# The appender's type specified as FileAppender, i.e. log output

# written to a file.


# The appender is assigned a layout SimpleLayout.

# SimpleLayout will include only priority level of the log

# statement and the log statement itself in log output.


Configuration file log4j.xml in XML format.

<?xml version="1.0" encoding="UTF-8" ?>
<!DOCTYPE log4j:configuration SYSTEM "log4j.dtd">
<log4j:configuration xmlns:log4j="">

<appender name="myAppender"
<layout class="org.apache.log4j.NAME_OF_LAYOUT"/>

<priority value="debug" />
<appender-ref ref="myAppender"/>


In order to use the config file in your logging application you must insert the following in the startup class of the application.

import org.apache.log4j.PropertyConfigurator;




The logger is the core component of the logging process. In log4j, there are 5 normal levels of logger available (not including custom Levels), the following is borrowed from the log4j API


  • static Level DEBUG
    • The DEBUG Level designates fine-grained informational events that are most useful to debug an application.
  • static Level INFO
    • The INFO level designates informational messages that highlight the progress of the application at coarse-grained level.
  • static Level WARN
    • The WARN level designates potentially harmful situations.
  • static Level ERROR
    • The ERROR level designates error events that might still allow the application to continue running.
  • static Level FATAL
    • The FATAL level designates very severe error events that will presumably lead the application to abort.

In addition, there are two special levels of logging available: (descriptions borrowed from the log4j API

  • static Level ALL
    • The ALL Level has the lowest possible rank and is intended to turn on all logging.
  • static Level OFF
    • The OFF Level has the highest possible rank and is intended to turn off logging.

The following ways can be used to make a logger:

  • Logger logger = Logger.getRootLogger();
  • Logger logger = Logger.getLogger("MyLogger");
  • static Logger logger = Logger.getLogger(test.class);

The last is the most common and to set its level:

  • logger.setLevel((Level)Level.WARN);


The following Appenders are available:

  1. ConsoleAppender: appends log events to System.out or System.err using a layout specified by the user. The default target is System.out.
  2. DailyRollingFileAppender extends FileAppender so that the underlying file is rolled over at a user chosen frequency.
  3. FileAppender appends log events to a file.
  4. RollingFileAppender extends FileAppender to backup the log files when they reach a certain size.
  5. WriterAppender appends log events to a Writer or an OutputStream depending on the user's choice.
  6. SMTPAppender sends an e-mail when a specific logging event occurs, typically on errors or fatal errors.
  7. SocketAppender sends LoggingEvent objects to a remote a log server, usually a SocketNode.
  8. SocketHubAppender sends LoggingEvent objects to a set of remote log servers, usually a SocketNodes
  9. SyslogAppendersends messages to a remote syslog daemon.
  10. TelnetAppender is a log4j appender that specializes in writing to a read-only socket.

An Appender can be created like this:


appender = new ConsoleAppender(new PatternLayout());


appender = null;

try {

appender = new FileAppender(new PatternLayout(),"filename");

} catch(Exception e) {}


appender = null;

try {

appender = new WriterAppender(new PatternLayout(),new FileOutputStream("filename"));

} catch(Exception e) {}


An appender must have one of these associated layouts:

  1. HTMLLayout formats the output as a HTML table.
  2. PatternLayout formats the output based on a conversion pattern specified, or if none is specified, the default conversion pattern.
  3. SimpleLayout formats the output in a very simple manner, it prints the Level, then a dash '-' and then the log message.


No comments: