Java language where a preprocessor is not available, log statements increase the size of the code and reduce its speed, even when logging is turned off. Reasonably sized application may contain thousands of log statements, speed is of particular importance. Ability to enable logging at runtime without modifying the application binary. Need a way to package log statements that can remain in shipped code without incurring a heavy performance cost. Logging behavior can be controlled by editing a configuration file, without touching the application binary.

Do programmers use debuggers or Loggers?

  • Logging is often faster then using a debugger.
  • Logging can be used to diagnose problems in the field.
  • Debugging is difficult in a distributed computing environment.

Note how similar this activities are.

  • Tracing
  • Debugging
  • Error Handling
  • Logging

All write output to a storage device. Only the type of information written is different.

Approaches to Logging

  • System.out.println
    • Poor performance
    • All or none – Example below
  • Custom log api
    • More code to maintain. Classic build vs buy (or use) decision
  • Open Source (like Log4j)
    • In this article, we’ll discuss Log4j

Log4j is the most popular logging package for Java. Sub-project of the logging services project at Apache ( . Formerly part of the Jakarta project. Used primarily as a debugging and auditing tool. Log4j claims to be fast and flexible: speed first, flexibility second. Although log4j has a many features, its first design goal was speed. Some log4j components have been rewritten many times to improve performance.

Limitations of logging to System.out.println

Prints every time. It can’t turn on and off at run-time without recompiling. It can’t turn on and off for specific classes or packages. Messages have no concept of severity. All messages are equally severe. Well, there’s System.err for the really bad messages. Only prints your message text. Doesn’t get timestamped, or marked with thread id’s automatically, or even the name of the class / method that called it. Difficult to change where the output goes. Application log messages get intermingled with server log messages . There’s only one System.out and only one System.err. Can’t log the same message to multiple destinations using System.out.println() and System.err.println(). Can’t make one log in text format and another in XML format. Can’t separate messages into separate logs by domain, subject, severity, who can fix, etc.

Log4j Architecture

Log4j has three main things in its architecture: loggers, appenders, and layouts. Loggers are the things you work with in code to send messages to. Appenders are output destinations. Layouts are the formats that appenders use to write their output.

A logger is what your code interacts with to request that a message be logged. It takes all message requests, regardless of level, severity, eventual destination, etc. Internally every logger has a java-class-like name. Dots between words work like package and sub-package separators.

Before using your loggers you need to make sure the log4j engine is configured. Typically this is done by reading a properties file, but can be done programmatically.

class Logger – basic methods


package org.apache.log4j; public class Logger
// Creation & retrieval methods:
public static Logger getRootLogger();
public static Logger getLogger(String name);
// printing methods:
public void trace(Object message);
public void debug(Object message);
public void info(Object message);
public void warn(Object message);
public void error(Object message);
public void fatal(Object message);
// generic printing method:
public void log(Level l, Object message);


To use a logger, log a message at the appropriate level of severity:

log.debug(“The value of x=“ + x);“System started at “ + new Date());
log.warn(“LDAP down – returning”);
log.error(“Could not access server”, excp);
log.fatal(“Cannot proceed”); System.exit();
Note that at any severity, you can optionally pass an exception as a parm

The logger will always accept your message. However, the logger might not always route it anywhere. Where it goes is a function of

  • the message severity
  • the logger’s name
  • what appenders are attached to it


  • Appenders are actual output destinations for the messages.
  • There are lots of different kinds of appenders, of which System.out (stdout) and System.err (stderr) are just two.
  • There are also appenders for files, Swing components, remote socket servers, JMS, NT Event loggers, and remote Unix Syslog daemons
  • Log4j allows attaching multiple appenders to any logger
  • Log4j allows appenders to be attached and removed from a logger dynamically
  • It is even possible for appenders to work asynchronously
  • You can also write your own, but there is rarely any need to

Commonly used Appenders

  • ConsoleAppender – sends messages to the console (stdout/stderr)
  • FileAppender – sends messages to a file (which you name)
  • RollingFileAppender – sends messages to a file, limited by length. Each time length threshold is exceeded, a new file is started, with a new suffix. You specify the main part of the file name and threshold size.
  • DailyRollingFileAppender – sends messages to a file, limited by time. Rolls over a new log file based on an interval (not limited to days) and suffixes the file with the date/time. You specify the main part of the file name and the interval.


Layouts are how appenders format the log messages sent to them by loggers. There are three layouts provided by log4j:

  • XMLLayout – format the logging event as an xml line.
  • HTMLLayout – format the logging event as an HTML table.
  • PatternLayout – format the logging event as a printf-like string

Configuring log4j

log4j is typically configured using a simple properties file. You can use an xml file but most people use a properties file. You can also do it programmatically, but to change things requires a recompile

At minimum, your config file:

  • Defines the root logger – Defines what severity level of messages should be allowed through. Defines what appender(s) the messages should go to
  • Defines at least one appender – This in turn usually requires the specification of one layout


Chainsaw is a GUI log4j log viewer written and maintained by the log4j team. Can receive logging events sent directly via TCP/IP. Can also load an XML-layout log file.

What’s the difference between log4j and Jakarta Commons Logging?
Jakarta Commons Logging (JCL) is an ultra-thin layer on top of log4j, the Avalon logkit (which nobody uses), and the JDK 1.4 logging API.  The idea is that you can use JCL and not worry about which logging implementation is underneath.
What’s the difference between log4j and the JDK 1.4 logging API?
The JDK logging API was clearly modeled after log4j.

log4j pros: market share, stable, more features, faster bug fixes(?)

JDK logging pros: no third party jars, core features are there

How much does it slow your app down?
Amazingly, not much.  Depends on how much you log.  You can actually do something (at the expense of lines of code) to make it even faster:
 if (log.isDebugEnabled()) {
Tagged with: JAVA

Leave a Reply

Your email address will not be published.

You may use these HTML tags and attributes: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <strike> <strong>


Looking for something?

Use the form below to search the site:

Still not finding what you're looking for? Drop a comment on a post or contact us so we can take care of it!

Related News Feeds

Set your Twitter account name in your settings to use the TwitterBar Section.