08 - log4j Layouts

8.1 Overview

Log4j comes with several built in layouts and allows us to create our own layouts also. As its name suggests, it is basically the layout of the log statements. The parent class of all layouts are org.apache.log4j.Layout which is an abstract class. Custom implementations of layout can either extends Layout class or any of its subclasses but directly extending Layout class is not recommended.

8.2 Layout API

As mentioned in overview, Layout class is available under org.apache.log4j package and is an abstract class. Layout class defines below three abstract methods

  1. public void activateOptions() – This method is defined in OptionHandler interface which is implemented by Layout class and is used to activate the options.
  2. public abstract boolean ignoresThrowable() – Thisis an abstract method which tells if the layout class will handle the throwable objects available in Logging Event  or not.
  3. public abstract String format(LoggingEvent event) –This is the main method of any layout class which does all the formatting of the event object and returns back the String representation of it. When we call a log event and passes the event object in it, appender class passes that log event object in format method and routes the output of format method to the destination.

8.3 log4j Built-in Layouts

Log4j comes with several built-in layouts. Some of them are-

  • DateLayout – This is again an abstract class which extends Layout class and is primarily used for date related formatting.
  • HTMLLayout-This layout extends Layout class and is a concrete class and formats the event object to Html tabular formatting which can be used in web reporting.
  • We can set the title of the html file and if we want to  display the location (line number) of code in HTMLLayout .
  • PatternLayout.- This is the most commonly used layout and uses String patterns which are configurable. We can specify the conversion pattern via configurations or programmatically.
  • SimpleLayout –SimpleLayout is the simplest format of logs which formats the log with log level and log message separated with hyphen (-)
  • XMLLayout – XMLLayout formats the logs in XML format with one entry of <log4j:event> tag for each log entry. We can specify if we want to  display the location (line number) of code in XMLLayout 

8.4 Example

8.4.1 Example 1 – HTMLLayout

Let's write an example to use the HTMLLayout.

  1. Create a log4j.xml in src folder with below content.
<?xml version="1.0" encoding="UTF-8" ?>
<!DOCTYPE log4j:configuration SYSTEM "log4j.dtd">
<log4j:configuration debug="true"
    xmlns:log4j='http://jakarta.apache.org/log4j/'>

    <appender name="file" class="org.apache.log4j.RollingFileAppender">
      <param name="append" value="false" />
      <param name="maxFileSize" value="10KB" />
      <param name="maxBackupIndex" value="5" />
      <param name="file" value="logs.html" />
      <layout class="org.apache.log4j.HTMLLayout">
        <param name="title" value="Log Title" />
               <param name="locationInfo" value="true" />
      </layout>
    </appender>

    <logger name="com.log4j.examples.Test"  additivity="false">
           <level value="ERROR"/>
           <appender-ref ref="file" />
    </logger>
</log4j:configuration>

  b.  Create a Test Class to log the messages

package com.log4j.examples;
import org.apache.log4j.Logger;
public class Test {

    static Logger logger = Logger.getLogger(Test.class);
    public static void main(String[] args) {

        logger.debug("Debug message ...");
        logger.error("Error message ... ");
        logger.fatal("fatal message ... ");
        logger.info(" Info message ... ");
        logger.trace(" trace message...");
        }
}

   c.  Run the above program and it will create the html file in src folder as shown below

Log4j exapmle to Create HTML File

8.4.2 Example 2 – PatternLayout

Lets write an example to use the PatternLayout.

  1. Create a log4j.xml in src folder with below content.
<?xml version="1.0" encoding="UTF-8" ?>
<!DOCTYPE log4j:configuration SYSTEM "log4j.dtd">
<log4j:configuration debug="true"
    xmlns:log4j='http://jakarta.apache.org/log4j/'>

   <appender name="console" class="org.apache.log4j.ConsoleAppender">
      <layout class="org.apache.log4j.PatternLayout">
        <param name="ConversionPattern" 
          value="%d{yyyy-MM-dd HH:mm:ss} %-5p %c{1}:%L - %m%n" />
      </layout>
   </appender>

  <root>
        <level value="DEBUG" />
        <appender-ref ref="console" />
  </root>

</log4j:configuration>

  b. Create a Test Class to log the messages

package com.log4j.examples;
import org.apache.log4j.Logger;
public class Test {

    static Logger logger = Logger.getLogger(Test.class);
    public static void main(String[] args) {

        logger.debug("Debug message ...");
        logger.error("Error message ... ");
        logger.fatal("fatal message ... ");
        logger.info(" Info message ... ");
        logger.trace(" trace message...");        
        }
}

 c.  Run the above program and it will print the log statement on console as shown below

2015-04-29 23:03:32 DEBUG Test:15 - Debug message ...
2015-04-29 23:03:32 ERROR Test:16 - Error message ... 
2015-04-29 23:03:32 FATAL Test:17 - fatal message ... 
2015-04-29 23:03:32 INFO  Test:18 -  Info message ...

8.4.3 Example 3 – SimpleLayout

Lets write an example to use the SimpleLayout.

  1. Create a log4j.xml in src folder with below content.
<?xml version="1.0" encoding="UTF-8" ?>
<!DOCTYPE log4j:configuration SYSTEM "log4j.dtd">
<log4j:configuration debug="true"
    xmlns:log4j='http://jakarta.apache.org/log4j/'>

    <appender name="console" class="org.apache.log4j.ConsoleAppender">
       <layout class="org.apache.log4j.SimpleLayout">
       </layout>
    </appender>

    <root>
        <level value="DEBUG" />
        <appender-ref ref="console" />
    </root>

</log4j:configuration>

  b.  Create a Test Class to log the messages

import org.apache.log4j.Logger;
public class Test {
   
    static Logger logger = Logger.getLogger(Test.class);
    public static void main(String[] args) {

        logger.debug("Debug message ...");
        logger.error("Error message ... ");
        logger.fatal("fatal message ... ");
        logger.info(" Info message ... ");
        logger.trace(" trace message...");        
       }
}

  c.  Run the above program and it will print the log statement on console as shown below. Log level and message is printed (delimited with hyphen (-))

DEBUG - Debug message ...
ERROR - Error message ... 
FATAL - fatal message ... 
INFO -  Info message ...

8.4.4 Example 4 – XMLLayout

Let’s write an example to use the XMLLayout.

  1. Create a log4j.xml in src folder with below content.
<?xml version="1.0" encoding="UTF-8" ?>
<!DOCTYPE log4j:configuration SYSTEM "log4j.dtd">
<log4j:configuration debug="true"
    xmlns:log4j='http://jakarta.apache.org/log4j/'>

    <appender name="console" class="org.apache.log4j.ConsoleAppender">
       <layout class="org.apache.log4j.xml.XMLLayout">
       </layout>
    </appender>
    <root>
        <level value="DEBUG" />
        <appender-ref ref="console" />
    </root>
</log4j:configuration>

  b. Create a Test Class to log the messages

package com.log4j.examples;
import org.apache.log4j.Logger;
public class Test {

    static Logger logger = Logger.getLogger(Test.class);
    public static void main(String[] args) {

        logger.debug("Debug message ...");
        logger.error("Error message ... ");
        logger.fatal("fatal message ... ");
        logger.info(" Info message ... ");
        logger.trace(" trace message...");
        }
}

   c.  Run the above program and it will print the log statement in XML format on console as shown below. One <log4j:event> tag for each log message.

<log4j:event logger="com.log4j.examples.Test" timestamp="1430329276780" level="DEBUG" thread="main">
<log4j:message><![CDATA[Debug message ...]]></log4j:message>
</log4j:event>

<log4j:event logger="com.log4j.examples.Test" timestamp="1430329276781" level="ERROR" thread="main">
<log4j:message><![CDATA[Error message ... ]]></log4j:message>
</log4j:event>

<log4j:event logger="com.log4j.examples.Test" timestamp="1430329276781" level="FATAL" thread="main">
<log4j:message><![CDATA[fatal message ... ]]></log4j:message>
</log4j:event>

<log4j:event logger="com.log4j.examples.Test" timestamp="1430329276781" level="INFO" thread="main">
<log4j:message><![CDATA[ Info message ... ]]></log4j:message>
</log4j:event>

Like us on Facebook