Log 4 J
Log 4 J
<[email protected]>
Copyright © 2005 The University Of Birmingham
Table of Contents
1. Introduction ................................................................................................................................................. 1
2. Installation .................................................................................................................................................. 1
3. log4j Basic Concepts ..................................................................................................................................... 1
3.1. Logger ............................................................................................................................................. 2
3.2. Appender .......................................................................................................................................... 3
3.2.1. Using A ConsoleAppender ........................................................................................................ 3
3.2.2. Using A FileAppender .............................................................................................................. 3
3.2.3. Using A WriterAppender .......................................................................................................... 3
3.3. Layout ............................................................................................................................................. 4
3.4. Basic Examples Illustrating this ............................................................................................................ 4
3.4.1. SimpleLayout and FileAppender ................................................................................................. 4
3.4.2. HTMLLayout and WriterAppender ............................................................................................. 4
3.4.3. PatternLayout and ConsoleAppender ........................................................................................... 5
4. Using External Configuration Files .................................................................................................................. 5
5. References (And links you may find useful) ....................................................................................................... 7
1. Introduction
Logging within the context of program development constitutes inserting statements into the program that provide some kind of
output information that is useful to the developer. Examples of logging are trace statements, dumping of structures and the familiar
System.out.println or printf debug statements. log4j offers a hierarchical way to insert logging statements within a Java program.
Multiple output formats and multiple levels of logging information are available.
By using a dedicated logging package, the overhead of maintaining thousands of System.out.println statements is alleviated as the
logging may be controlled at runtime from configuration scripts. log4j maintains the log statements in the shipped code. By for-
malising the process of logging, some feel that one is encouraged to use logging more and with higher degree of usefulness.
2. Installation
In order to use the tools we are about to install it is necessary to setup the operating environment so that the tools know where to
find stuff they need and the operating system knows where to find the tools. A understanding of how to do this is essential as you
will be asked to change the operating environment. I have comprehensively covered this in documents entitled Configuring A Win-
dows Working Environment [../winenvars/winenvarshome.html] and Configuring A Unix Working Environment
[../unixenvars/unixenvarshome.html].
3.1. Logger
The logger is the core component of the logging process. In log4j, there are 5 normal levels Levels of logger available (not includ-
ing custom Levels), the following is borrowed from the log4j API (http://jakarta.apache.org/log4j/docs/api/index.html):
In addition, there are two special levels of logging available: (descriptions borrowed from the log4j API
http://jakarta.apache.org/log4j/docs/api/index.html):
A logger will only output messages that are of a level greater than or equal to it. If the level of a logger is not set it will inherit the
level of the closest ancestor. So if a logger is created in the package com.foo.bar and no level is set for it, it will inherit the level of
the logger created in com.foo. If no logger was created in com.foo, the logger created in com.foo.bar will inherit the level of the
root logger, the root logger is always instantiated and available, the root logger is assigned the level DEBUG.
There are a number of ways to create a logger, one can retrieve the root logger:
Logger logger = Logger.getRootLogger();
One can create a new logger:
2
Log4J
3.2. Appender
The Appender controls how the logging is output. The Appenders available are (descriptions borrowed from the log4j API
http://jakarta.apache.org/log4j/docs/api/index.html):
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.
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.
8. SocketHubAppender sends LoggingEvent objects to a set of remote log servers, usually a SocketNodes
One may also implement the Appender interface to create ones own ways of outputting log statements.
So that one may choose whether or not to append the file specified or not. If this is not specified, the default is to append.
3
Log4J
This WriterAppender uses the constructor that takes a PatternLayout and an OutputStream as arguments, in this case a FileOutput-
Stream is used to output to a file, there are other constructors available.
3.3. Layout
The Appender must have have an associated Layout so it knows how to format the output. There are three types of Layout avail-
able:
2. PatternLayout formats the output based on a conversion pattern specified, or if none is specified, the default conversion pat-
tern.
3. SimpleLayout formats the output in a very simple manner, it prints the Level, then a dash '-' and then the log message.
import org.apache.log4j.Level;
import org.apache.log4j.Logger;
import org.apache.log4j.SimpleLayout;
import org.apache.log4j.FileAppender;
public class simpandfile {
static Logger logger = Logger.getLogger(simpandfile.class);
public static void main(String args[]) {
SimpleLayout layout = new SimpleLayout();
FileAppender appender = null;
try {
appender = new FileAppender(layout,"output1.txt",false);
} catch(Exception e) {}
logger.addAppender(appender);
logger.setLevel((Level) Level.DEBUG);
logger.debug("Here is some DEBUG");
logger.info("Here is some INFO");
logger.warn("Here is some WARN");
logger.error("Here is some ERROR");
logger.fatal("Here is some FATAL");
}
}
You can download it: simpandfile.java [files/simpandfile.java]. And checkout the output produced: output1.txt [files/output1.txt].
import java.io.*;
import org.apache.log4j.Level;
import org.apache.log4j.Logger;
import org.apache.log4j.HTMLLayout;
import org.apache.log4j.WriterAppender;
public class htmlandwrite {
static Logger logger = Logger.getLogger(htmlandwrite.class);
public static void main(String args[]) {
HTMLLayout layout = new HTMLLayout();
WriterAppender appender = null;
try {
FileOutputStream output = new FileOutputStream("output2.html");
appender = new WriterAppender(layout,output);
} catch(Exception e) {}
logger.addAppender(appender);
4
Log4J
logger.setLevel((Level) Level.DEBUG);
logger.debug("Here is some DEBUG");
logger.info("Here is some INFO");
logger.warn("Here is some WARN");
logger.error("Here is some ERROR");
logger.fatal("Here is some FATAL");
}
}
You can download it: htmlandwrite.java [files/htmlandwrite.java]. And checkout the output produced: output2.html
[files/output2.html].
import org.apache.log4j.Level;
import org.apache.log4j.Logger;
import org.apache.log4j.PatternLayout;
import org.apache.log4j.ConsoleAppender;
public class consandpatt {
static Logger logger = Logger.getLogger(consandpatt.class);
public static void main(String args[]) {
// Note, %n is newline
String pattern = "Milliseconds since program start: %r %n";
pattern += "Classname of caller: %C %n";
pattern += "Date in ISO8601 format: %d{ISO8601} %n";
pattern += "Location of log event: %l %n";
pattern += "Message: %m %n %n";
PatternLayout layout = new PatternLayout(pattern);
ConsoleAppender appender = new ConsoleAppender(layout);
logger.addAppender(appender);
logger.setLevel((Level) Level.DEBUG);
logger.debug("Here is some DEBUG");
logger.info("Here is some INFO");
logger.warn("Here is some WARN");
logger.error("Here is some ERROR");
logger.fatal("Here is some FATAL");
}
}
You can download it: consandpatt.java [files/consandpatt.java]. And checkout the output produced: output2.txt [files/output2.txt].
The file starts with a standard XML declaration followed by a DOCTYPE declaration which indicates the DTD(Document Type
Definition), this defines the structure of the XML file, what elements may be nested within other elements etc. This file is pro-
vided in the log4j distribution under src/java/org/apache/log4j/xml. Next comes the all-encapsulating log4j:configuration
element, which was specified as the root element in the DOCTYPE declaration. Nested within the root element are two structures:
5
Log4J
Here an Appender is created and called "ConsoleAppender", note that any name could have been chosen, it is because of the con-
trivity of examples that this name was chosen. The class for the appender is then specified in full, when referring to classes, one al-
ways uses the fully qualified class name. An Appender must always have a name and a class specified. Nested within Appender is
the layout element which defines the layout to be a SimpleLayout. Layout must always have the class attribute.
<root>
<priority value ="debug" />
<appender-ref ref="ConsoleAppender"/>
</root>
The root element always exists and cannot be sub-classed. The example shows the priority being set to "debug" and the appender
setup by including an appender-ref element, of which, more that one may be specified. See the file src/
java/org/apache/log4j/xml/log4j.dtd in your log4j distribution for more information about the structure of an XML con-
figuration file. The configuration file is pulled into the Java program like this:
DOMConfigurator.configure("configurationfile.xml");
The DOMConfigurator is used to initialise the log4j environment using a DOM tree. Here is the example xml configuration file:
plainlog4jconfig.xml [files/plainlog4jconfig.xml]. Here is a program which implements this configuration file: files/ex-
ternalxmltest.java [externalxmltest.java]:
import org.apache.log4j.Logger;
import org.apache.log4j.xml.DOMConfigurator;
public class externalxmltest {
static Logger logger = Logger.getLogger(externalxmltest.class);
public static void main(String args[]) {
DOMConfigurator.configure("xmllog4jconfig.xml");
logger.debug("Here is some DEBUG");
logger.info("Here is some INFO");
logger.warn("Here is some WARN");
logger.error("Here is some ERROR");
logger.fatal("Here is some FATAL");
}
}
Here is an XML configuration file for a Logger implementing a FileAppender using a PatternLayout:
You can download this example from here: xmllog4jconfig2.xml [files/xmllog4jconfig2.xml]. For more examples of using xml
files to configure a log4j environment, see the src/java/org/apache/log4j/xml/examples/ directory in the log4j distribu-
tion.
Here is the configuration file discussed above, expressed in the form of a plain text file:
You can download it here: plainlog4jconfig.txt [files/plainlog4jconfig.txt]. Here is a program implementing this:
import org.apache.log4j.Logger;
import org.apache.log4j.PropertyConfigurator;
public class externalplaintest {
static Logger logger = Logger.getLogger(externalplaintest.class);
public static void main(String args[]) {
PropertyConfigurator.configure("plainlog4jconfig.xml");
logger.debug("Here is some DEBUG");
logger.info("Here is some INFO");
logger.warn("Here is some WARN");
logger.error("Here is some ERROR");
logger.fatal("Here is some FATAL");
}
}
You can download an example program that uses this configuration file here: files/externalplaintest.java. For more ex-
amples of using plain text files to configure a log4j environment, see the examples directory in the log4j distribution.
The use of external example files has only been briefly discussed here, it is assumed that you have the capacity to learn more by
yourself by studying the examples provided with the log4j distribution and experimenting.
• http://jakarta.apache.org/log4j/docs/manual.html
Short introduction to log4j - Ceki Gülcü - March 2002
• http://www.vipan.com/htdocs/log4jhelp.html
Don't Use System.out.println! Use Log4j - Vipan Singla
• http://www.opensymphony.com/guidelines/logging.jsp
LOG4J / OpenSymphony Logging Primer
• http://builder.com.com/article.jhtml?id=u00820020124kev01.htm
Add logging to your Java Applications - Kevin Brown