log4j PatternLayout
If you want to generate your logging information in a particular format based on a patten then you can use org.apache.log4j.PatternLayout to format your logging information.
The PatternLayout class extends the abstract org.apache.log4j.Layout class and overrides the format() method to structure logging information according to a supplied pattern.
PatternLayout is also a simple Layout object that provides following Bean Property which can be set using configuration file:
Pattern Conversion Characters:
Below table explains characters used in the above pattern and all other characters which you can use in your custom pattern:
Format Modifiers:
By default the relevant information is output as is. However, with the aid of format modifiers it is possible to change the minimum field width, the maximum field width and justification.
Following table covers various modifiers scenarios:
PatternLayout Example:
Following is a simple configuration file for PatternLayout:
# 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}/log.out
# Define the layout for file appender
log4j.appender.FILE.layout=org.apache.log4j.PatternLayout
log4j.appender.FILE.layout.ConversionPattern=%d{yyyy-MM-dd}-%t-%x-%-5p-%-10c:%m%n
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 a log.out file in /usr/home/log4j directory which would have following log information:
2010-03-23-main--DEBUG-log4jExample:Hello this is an debug message
2010-03-23-main--INFO -log4jExample:Hello this is an info message
No comments:
Post a Comment