Home » Log4j HTMLLayout

Log4j HTMLLayout

by Online Tutorials Library

Log4j – HTMLLayout

Log4j provides multiple options to format log files created by the framework. It can create simple log files, xml log files or html log files also.

If you want to create your logging information in an HTML formatted file, then you have to use the org.apache.HTMLLayout class to format your logging information.

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

HTMLLayout displays the following information:

  • The time elapsed from the start of the application before a particular logging event was generated.
  • The thread name that invoked the logging request.
  • Level associated with this logging request.
  • Name of the logger and logging message.
  • The location information (optional) for the program file and the line number from which this logging was invoked.

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

S. No. Method Description
1. setContentType(String) This method is used to set the content type of the text/html HTML content. Default is text/html.
2. setLocationInfo(String) This method is used to set the location information for the logging event. Default is false.
3. setTitle(String) This method is used to set the title for the HTML file. Default is log4j Log Messages.

HTMLLayoutExample

Following is the simple configuration file for HTMLLayout:

Log4j.properties:

Following is the Java file which would generate logging information:

HtmlLayoutEx.java

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

htmlLayout.html

Log4j HTMLLayout

You can use any web browser to open htmlLayout.html file. You can note that the footer for the </html> and </body> tags is completely missing.

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


You may also like