java Api

Log4j


Simple Log4j Configuration
Log4j is a simple and flexible logging framework. In this tutorial you will learn how to configure log4j for your applications. Let's get started first download the latest version of log4j (Download ). I am using log4j version 1.2.15. Add the log4j-1.2.15.jar to the classpath.
Next you need to create an instance of Logger class. You can create one using theLogger.getLogger(HelloWorld.class) method. It takes one argument the fully qualified class name.
Now we need to configure log4j. The simple way to do that is using BasicConfigurator. configure() method. This will log all the messages on the console.
Now everything is ready you can log messages using any of the print statements of theLogger class. In the following code I use the debug() method to display the "HelloWorld!" message.

01.package com.helloworld;
02.
03.import org.apache.log4j.BasicConfigurator;
04.import org.apache.log4j.Logger;
05.
06.public class HelloWorld {
07.
08.static final Logger logger = Logger.getLogger(HelloWorld.class);
09.
10.public static void main(String[] args) {
11.BasicConfigurator.configure();
12.logger.debug("Hello World!");
13.}
14.}
The other methods available are info(), warn(), error() and fatal(). Each method represents a logger level namely DEBUG, INFO, WARN, ERROR and FATAL.
The following example shows how to use these methods.
01.package com.helloworld;
02.
03.import org.apache.log4j.BasicConfigurator;
04.import org.apache.log4j.Logger;
05.
06.public class HelloWorld {
07.
08.static final Logger logger = Logger.getLogger(HelloWorld.class);
09.
10.public static void main(String[] args) {
11.BasicConfigurator.configure();
12.logger.debug("Sample debug message");
13.logger.info("Sample info message");
14.logger.warn("Sample warn message");
15.logger.error("Sample error message");
16.logger.fatal("Sample fatal message");
17.}
18.}

Log4j Configuration Using Properties File
Log4j will be usually configured using a properties file or xml file externally. So once the log statements are in place you can easily control them using the external configuration file without modifying the source code. Now let's see how you can obtain the same log output as the previous example using the properties file configuration.

Three main components you need to configure to obtain the same result are the logger, appender and layout. The logger object is the one that is used to log messages, appender is the one that specifies the output destination like console or a file and layout is the one that specify the format in which the log messages should be logged.

When you configure using the Basic Configurator.configure() method by default it uses the ConsoleAppender and PatternLayout for all the loggers.

The following configuration creates the same result as the BasicConfigurator.configure()method.
1.log4j.rootLogger=DEBUG, CA
2.
3.log4j.appender.CA=org.apache.log4j.ConsoleAppender
4.
5.log4j.appender.CA.layout=org.apache.log4j.PatternLayout
6.log4j.appender.CA.layout.ConversionPattern=%-4r [%t] %-5p %c %x - %m%n

The rootLogger is the one that resides on the top of the logger hierarchy. Here we set its level to DEBUG and added the console appender (CA) to it. The console appender can have arbitrary name, here its name is CA.
You need to create an appender as shown and set its layout to PatternLayout. ThePatternLayout uses the ConversionPattern to format the message. To know more about the various formating options you can refer the documentation. ( PatternLayout )

Once the appender is created and its layout is set you need to specify which loggers can use this appender. If you set this appender to the rootLogger then all the loggers will log messge to this appender. Since the rootLogger is on top of the hierarchy all the loggers will inherit its logger level and its appenders. You will see this in more detail in the comming examples.

Here is our example code.
01.package com.helloworld;
02.
03.import org.apache.log4j.Logger;
04.import org.apache.log4j.PropertyConfigurator;
05.
06.public class HelloWorld {
07.
08.static final Logger logger = Logger.getLogger(HelloWorld.class);
09.
10.public static void main(String[] args) {
11.PropertyConfigurator.configure("log4j.properties");
12.logger.debug("Sample debug message");
13.logger.info("Sample info message");
14.logger.warn("Sample warn message");
15.logger.error("Sample error message");
16.logger.fatal("Sample fatal message");
17.}
18.}
You need to use the PropertyConfigurator.configure() method to configure log4j using a properties file. Log4j should be configured only once for the entire application.

Log4j Multiple Appender Example


In this example you will see how to create a console and file appender and add it to the rootLogger.
The log4j.properties file is shown below.
01.log4j.rootLogger=DEBUG, CA, FA
02.
03.#Console Appender
04.log4j.appender.CA=org.apache.log4j.ConsoleAppender
05.log4j.appender.CA.layout=org.apache.log4j.PatternLayout
06.log4j.appender.CA.layout.ConversionPattern=%-4r [%t] %-5p %c %x - %m%n
07.
08.#File Appender
09.log4j.appender.FA=org.apache.log4j.FileAppender
10.log4j.appender.FA.File=sample.log
11.log4j.appender.FA.layout=org.apache.log4j.PatternLayout
12.log4j.appender.FA.layout.ConversionPattern=%-4r [%t] %-5p %c %x - %m%n
13.
14.# Set the logger level of File Appender to WARN
15.log4j.appender.FA.Threshold = WARN

Here we create two appenders ConsoleAppender and FileAppender. You need to set the Fileattribute of the FileAppender to the log file name, here it is sample.log. Add theFileAppender (FA) and the ConsoleAppender (CA) to the rootLogger.

You can also set the logger level for each appender seperately. Here the FileAppender logger level is set to WARN. Only WARN, ERROR and FATAL level log messages will be logged in thesample.log file. Since we don't set any log level explicitly for the ConsoleAppender it will inherit the rootLogger level, that is DEBUG.

Here is our example code.
01.package com.helloworld;
02.
03.import org.apache.log4j.Logger;
04.import org.apache.log4j.PropertyConfigurator;
05.
06.public class HelloWorld {
07.
08.static final Logger logger = Logger.getLogger(HelloWorld.class);
09.
10.public static void main(String[] args) {
11.PropertyConfigurator.configure("log4j.properties");
12.logger.debug("Sample debug message");
13.logger.info("Sample info message");
14.logger.warn("Sample warn message");
15.logger.error("Sample error message");
16.logger.fatal("Sample fatal message");
17.}
18.}

Log4j File Appender
A typical requirement in the project is to log different modules in different log files. For instance in this example we have two modules one for the admin and other for reports.
To do this we create two seperate FileAppenders and associate them with each package.
01.log4j.rootLogger=DEBUG
02.
03.# AdminFileAppender - used to log messages in the admin.log file.
04.log4j.appender.AdminFileAppender=org.apache.log4j.FileAppender
05.
06.log4j.appender.AdminFileAppender.File=admin.log
07.
08.log4j.appender.AdminFileAppender.layout=org.apache.log4j.PatternLayout
09.log4j.appender.AdminFileAppender.layout.ConversionPattern= %-4r [%t] %-5p %c %x - %m%n
10.
11.# ReportFileAppender - used to log messages in the report.log file.
12.log4j.appender.ReportFileAppender=org.apache.log4j.FileAppender
13.
14.log4j.appender.ReportFileAppender.File=report.log
15.
16.log4j.appender.ReportFileAppender.layout=org.apache.log4j.PatternLayout
17.log4j.appender.ReportFileAppender.layout.ConversionPattern= %-4r [%t] %-5p %c %x - %m%n
18.
19.log4j.logger.com.vaannila.admin=WARN,AdminFileAppender
20.log4j.logger.com.vaannila.report=DEBUG,ReportFileAppender

Here instead of associating the appenders to the rootLogger we associate it with different packages. The AdminFileAppender is linked with the admin package and the ReportFileAppenderis linked with the report package. This means all the log entries in the admin module will be logged in the admin.log file and all the log entries in the report module will be logged in the report.logfile. You can also set different logger levels for each package, here for the admin package it is set to WARN and for the report package it is set to DEBUG. The rootLogger will be by default set to the logger level DEBUG, so this statement "log4j.rootLogger=DEBUG" is there only for your understanding purpose and it is not necessary.

In this example we have two classes SampleAdmin class in the admin package and SampleReportclass in the report package.
01.package com..admin;
02.
03.import org.apache.log4j.Logger;
04.import org.apache.log4j.PropertyConfigurator;
05.
06.import com.report.SampleReport;
07.
08.public class SampleAdmin {
09.
10.static Logger logger = Logger.getLogger(SampleAdmin.class);
11.
12.public static void main(String[] args) {
13.PropertyConfigurator.configure("log4j.properties");
14.logger.debug("Sample debug message");
15.logger.info("Sample info message");
16.logger.warn("Sample warn message");
17.logger.error("Sample error message");
18.logger.fatal("Sample fatal message");
19.SampleReport obj = new SampleReport();
20.obj.generateReport();
21.}
22.
23.}
01.package com.report;
02.
03.import org.apache.log4j.Logger;
04.
05.public class SampleReport {
06.
07.static Logger logger = Logger.getLogger(SampleReport.class);
08.
09.public void generateReport()
10.{
11.logger.debug("Sample debug message");
12.logger.info("Sample info message");
13.logger.warn("Sample warn message");
14.logger.error("Sample error message");
15.logger.fatal("Sample fatal message");
16.}
17.}

Log4j XML Configuration
We can also use XML file to configure log4j. In the previous example we saw how we can do this using the properties file, everything remains the same except that we use the XML configuration file here.
The following code shows the log4j.properties file we used in the previous example.
1.log4j.rootLogger=DEBUG, CA
2.log4j.appender.CA=org.apache.log4j.ConsoleAppender
3.log4j.appender.CA.layout=org.apache.log4j.PatternLayout
4.log4j.appender.CA.layout.ConversionPattern=%-4r [%t] %-5p %c %x - %m%n

The following code shows the log4j.properties file we used in the previous example.
1.log4j.rootLogger=DEBUG, CA
2.log4j.appender.CA=org.apache.log4j.ConsoleAppender
3.log4j.appender.CA.layout=org.apache.log4j.PatternLayout
4.log4j.appender.CA.layout.ConversionPattern=%-4r [%t] %-5p %c %x - %m%n
The following code shows the corresponding log4j.xml file.
01.<?xml version="1.0" encoding="UTF-8" ?>
02.<!DOCTYPE log4j:configuration SYSTEM "log4j.dtd">
03.<log4j:configuration xmlns:log4j='http://jakarta.apache.org/log4j/'>
04.<appender name="CA" class="org.apache.log4j.ConsoleAppender">
05.<layout class="org.apache.log4j.PatternLayout">
06.<param name="ConversionPattern" value="%-4r [%t] %-5p %c %x - %m%n" />
07.</layout>
08.</appender>
09.<root>
10.<level value="debug" />
11.<appender-ref ref="CA" />
12.</root>
13.</log4j:configuration>


To configure log4j using xml file we use DOMConfigurator.configure() method.
01.package com.helloworld;
02.
03.import org.apache.log4j.Logger;
04.import org.apache.log4j.xml.DOMConfigurator;
05.
06.public class HelloWorld {
07.
08.static Logger logger = Logger.getLogger(HelloWorld.class);
09.
10.public static void main(String[] args) {
11.DOMConfigurator.configure("log4j.xml");
12.logger.debug("Sample debug message");
13.logger.info("Sample info message");
14.logger.warn("Sample warn message");
15.logger.error("Sample error message");
16.logger.fatal("Sample fatal message");
17.}
18.}

Log4j XML Configuration
In this example we will see how to create more than one appender using xml configuration file. This example is similar to the one we saw before using the properties file (example). So I will simply compare both.
The following code shows the log4j.properties file we used in the previous example.

01.log4j.rootLogger=DEBUG, CA, FA
02. 
03.#Console Appender
04.log4j.appender.CA=org.apache.log4j.ConsoleAppender
05.log4j.appender.CA.layout=org.apache.log4j.PatternLayout
06.log4j.appender.CA.layout.ConversionPattern=%-4r [%t] %-5p %c %x - %m%n
07. 
08.#File Appender
09.log4j.appender.FA=org.apache.log4j.FileAppender
10.log4j.appender.FA.File=sample.log
11.log4j.appender.FA.layout=org.apache.log4j.PatternLayout
12.log4j.appender.FA.layout.ConversionPattern=%-4r [%t] %-5p %c %x - %m%n
13. 
14.# Set the logger level of File Appender to WARN
15.log4j.appender.FA.Threshold = WARN
The following code shows the corresponding log4j.xml file.
01.<?xml version="1.0" encoding="UTF-8" ?>
02.<!DOCTYPE log4j:configuration SYSTEM "log4j.dtd">
03.<log4j:configuration xmlns:log4j='http://jakarta.apache.org/log4j/'>
04.<appender name="CA" class="org.apache.log4j.ConsoleAppender">
05.<layout class="org.apache.log4j.PatternLayout">
06.<param name="ConversionPattern" value="%-4r [%t] %-5p %c %x - %m%n" />
07.</layout>
08.</appender>
09.<appender name="FA" class="org.apache.log4j.FileAppender">
10.<param name="File" value="sample.log"/>
11.<param name="Threshold" value="WARN"/>
12.<layout class="org.apache.log4j.PatternLayout">
13.<param name="ConversionPattern" value="%-4r [%t] %-5p %c %x - %m%n" />
14.</layout>
15.</appender>
16.<root>
17.<level value="DEBUG" />
18.<appender-ref ref="CA" />
19.<appender-ref ref="FA" />
20.</root>
21.</log4j:configuration>