log4j - HTMLLayout



If you want to generate your logging information in an HTML-formatted file, then you can use org.apache.log4j.HTMLLayout to format your logging information.

The HTMLLayout class extends the abstract org.apache.log4j.Layout class and overrides the format() method from its base class to provide HTML-style formatting.

It provides the following information to be displayed:

  • The time elapsed from the start of the application before a particular logging event was generated.

  • The name of the thread that invoked the logging request.

  • The level associated with this logging request.

  • The name of the logger and logging message.

  • The optional location information for the program file and the line number from which this logging was invoked.

HTMLLayout is a very simple Layout object that provides the following methods:

Sr.No. Method & Description
1 setContentType(String)

Sets the content type of the text/html HTML content. Default is text/html.

2 setLocationInfo(String)

Sets the location information for the logging event. Default is false.

3 setTitle(String)

Sets the title for the HTML file. Default is log4j Log Messages.

HTMLLayout Example

Following is a simple configuration file for HTMLLayout:

# Define the root logger with appender file
log = /usr/home/log4j
log4j.rootLogger = DEBUG, FILE

# Define the file appender
log4j.appender.FILE=org.apache.log4j.FileAppender
log4j.appender.FILE.File=${log}/htmlLayout.html

# Define the layout for file appender
log4j.appender.FILE.layout=org.apache.log4j.HTMLLayout
log4j.appender.FILE.layout.Title=HTML Layout Example
log4j.appender.FILE.layout.LocationInfo=true

Now consider the following Java Example which would generate logging information:

import org.apache.log4j.Logger;

import java.io.*;
import java.sql.SQLException;
import java.util.*;

public class log4jExample{
   /* Get actual class name to be printed on */
   static Logger log = Logger.getLogger(log4jExample.class.getName());
   
   public static void main(String[] args)throws IOException,SQLException{
      log.debug("Hello this is an debug message");
      log.info("Hello this is an info message");
   }
}

Compile and run the above program. It would create an htmlLayout.html file in /usr/home/log4j directory which would have the following log information:

Log session start time Mon Mar 22 13:30:24 AST 2010

Time Thread Level Category File:Line Message
0 main DEBUG log4jExample log4jExample.java:15 Hello this is an debug message
6 main INFO log4jExample log4jExample.java:16 Hello this is an info message

You would use a web browser to open htmlLayout.html file. It is also important to note that the footer for the </html> and </body> tags is completely missing.

One of the big advantages of having the log file in HTML format is that it can be published as a web page for remote viewing.

log4j_log_formatting.htm
Advertisements