Log4j

Log4j XML Configuration Example

In this example we will see how to configure Log4j using XML. You can use the property file as well but now  days xml is preferred over property file. Note that unlike Log4j 1.x, the public Log4j 2 API does not expose methods to add, modify or remove appenders and filters or manipulate the configuration in any way.

In this example we are usign Java 1.6 and maven. We will create a simple HelloLog4J class with the main method which will call the LOGGER.debug() and LOGGER.info() methods.
 
 
 

1. Project Structure

The below image shows the project structure.

Figure 1. Project Structure


2. Java Class

Below is the HelloLog4J class which uses org.apache.log4j.Logger class to print the log data on console.

HelloLog4J.java

import org.apache.log4j.Logger;

/**
 * Example class for Log4J XML Configuration
 * @author JavaCodeGeeks
 */
public class HelloLog4J {
    private static final Logger LOGGER = Logger.getLogger(HelloLog4J.class);
    public static void main(String a[]) {
        System.out.println("Hello Log4J");
        LOGGER.debug("Logger Debug");
        LOGGER.info("Logger Info");
    }
}

3. Log4j Configuration file

Below is the log4j.xml file.

log4j.xml

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

<log4j:configuration xmlns:log4j="http://jakarta.apache.org/log4j/">
    <appender name="console" class="org.apache.log4j.ConsoleAppender">
        <param name="Target" value="System.out"/>
        <layout class="org.apache.log4j.PatternLayout">
            <param name="ConversionPattern" value="%-5p %c{1} - %m%n"/>
        </layout>
    </appender>
    <root>
        <priority value ="debug" />
        <appender-ref ref="console" />
    </root>
</log4j:configuration>

This will print all debug or higher messages to the console/screen.

3.1 Appender

The appender is defined first, with a name (in this case “console“). A layout is defined for the appender (in this case  PatternLayout ), and a pattern is defined for the layout.

ConsoleAppender appends log events to System.out or System.err using a layout specified by the user. The default target is System.out.The other commonly used appender is org.apache.log4j.FileAppender. FileAppender appends log events to a file. Below is the example of  FileAppender.

    <appender name="fileAppender" class="org.apache.log4j.FileAppender">
        <param name="File" value="/example/log4j.log" />
        <param name="Append" value="true" />
        <layout class="org.apache.log4j.PatternLayout">
          <param name="ConversionPattern" value="%t %-5p %c{2} - %m%n"/>
        </layout>
    </appender>

File is the full path to the log file.

Append – ‘true’ to append the file, ‘false’ to truncate the file

The JMSAppender will publish logging information to a JMS Topic specified in the log4 configuration file

3.2 Filter Configuration

Filters can be defined at appender level. For example, to filter only certain levels, the LevelRangeFilter can be used like this:

 <appender name="fileAppender" class="org.apache.log4j.FileAppender">
    <layout class="org.apache.log4j.PatternLayout">
        <param name="ConversionPattern" value="[%t] %-5p %c - %m%n" />
    </layout>
    <filter class="org.apache.log4j.varia.LevelRangeFilter">
        <param name="levelMin" value="WARN" />
        <param name="levelMax" value="WARN" />
    </filter>
</appender>

SocketHubAppender sends LoggingEvent objects to a set remote a log servers, usually a SocketNode.
The SMTP Appender sends an email through SMTP for each logged message. The below configuration will email any log message that is an warning or higher:

<appender name="emailAppender" class="org.apache.log4j.net.SMTPAppender">
    <param name="BufferSize" value="1024" />
    <param name="SMTPHost" value="javacodegeeks.smtp.host" />
    <param name="From" value="admin@javacodegeeks.com" />
    <param name="To" value="user1@yahoo.com.com,user2@yahoo.com" />
    <param name="Subject" value="Log4J XML Configuration Example" />
    <layout class="org.apache.log4j.PatternLayout">
        <param name="ConversionPattern" value="[%t] %-5p %c - %m%n" />
    </layout>
    <filter class="org.apache.log4j.varia.LevelRangeFilter">
        <param name="LevelMin" value="WARN" />
        <param name="LevelMax" value="FATAL" />
    </filter>
</appender>

4. Layout

There are different kinds of layouts used, for e.g:

  • org.apache.log4j.helpers.DateLayout
  • org.apache.log4j.HTMLLayout
  • org.apache.log4j.PatternLayout
  • org.apache.log4j.SimpleLayout
  • org.apache.log4j.xml.XMLLayout

The most commonly used layout is PatternLayout. There are some synchronization issues with this which are overcome by org.apache.log4j.EnhancedPatternLayout. This layout formats the logging event and return the result as String. The output depends on the conversion pattern. A conversion pattern is composed of literal text and format control expressions called conversion specifiers. You can insert any literal text in the conversion pattern. Each conversion specifier starts with a percent sign (%) and is followed by optional format modifiers and a conversion character. The conversion character specifies the type of data, e.g. category, priority, date, thread name. The format modifiers control such things as field width, padding, left and right justification.

SimpleLayout consists of the level of the log statement, followed by ” – ” and then the log message itself. For example,

INFO - Java Rocks!!!

5. Logger

The most important logger is the root logger. Other loggers inherit from the root, so if we don’t define any other logger all will use console appender. Note that by default Log4j assigns the root logger to Level.ERROR. Root logger resides at the top of the logger hierarchy. It is exceptional in two ways:

  • it always exists,
  • it cannot be retrieved by name.

Invoking the class static Logger.getRootLogger method retrieves it. All other loggers are instantiated and retrieved with the class static Logger.getLogger method. This method takes the name of the desired logger as a parameter

6. Maven

Below is the pom.xml which defines the dependency

pom.xml

<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0"
 xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
 xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
 <modelVersion>4.0.0</modelVersion>

     <groupId>com.javacodegeek</groupId>
     <artifactId>log4j</artifactId>
     <version>1.0-SNAPSHOT</version>

     <dependencies>

         <dependency>
             <groupId>log4j</groupId>
             <artifactId>log4j</artifactId>
             <version>1.2.17</version>
         </dependency>

     </dependencies>

</project>

I have used IDEA IntelliJ IDE version 14.0 to develop this. You can use your choice of IDE. If you are using IntelliJ, right click on the HelloLog4J java file and click ‘Run HelloLog4J.main()’

Figure 2. Run Java Code

7. Output

Below is the result I got

Figure 3. Output

8. Download source code

Download
You can download the full source code of this example here : Log4j XML Configuration Example.zip

Mohammad Meraj Zia

Senior Java Developer
Subscribe
Notify of
guest

This site uses Akismet to reduce spam. Learn how your comment data is processed.

1 Comment
Oldest
Newest Most Voted
Inline Feedbacks
View all comments
Dat
Dat
3 years ago

good

Back to top button