Thursday, February 19, 2009

Log4j

Log4j, I think, means "log for java". It is an useful tool to show the list of debugging or running log. Log4j has 6 levels, which are FATAL, ERROR, WARN, INFO, DEBUG and TRACE.
There are two ways to configure log4j. One is with a properties file, named log4j.properties, and the other is with an XML file. Within either these 3 components are necessary: Loggers, Appenders and Layouts. Configuring logging via a file has the advantage of turning logging on or off without modifying the application that uses log4j.
Loggers are logical log file names; The actual outputs are done by Appenders. Appenders use Layouts to format log entries.
To debug a misbehaving configuration use the Java VM Property - Dlog4j.debug which will ouput to standard out. To find out where a log4j.properties was loaded from inspect getClass().getResource("/log4j.properties");
Here is An Example Samuel wrote, which is the content of log4j.properties in /Main/Resource.

# The root logger is assigned priority level info and it's appender is stdout
log4j.rootLogger=info, stdout

# stdout
log4j.appender.stdout=org.apache.log4j.ConsoleAppender
log4j.appender.stdout.layout=org.apache.log4j.PatternLayout
log4j.appender.stdout.layout.ConversionPattern=%d{dd/MM/yy HH:mm:ss} %c{1} %p - %m%n

# limit categories
log4j.logger.com.tt.netcomp=INFO

He said actually he diddn't use log4j directedly, but use Commons Logging(JCL) instead, whose backend includes Log4j.
This sentence, "log4j.appender.stdout=org.apache.log4j.ConsoleAppender" is to write log information out to the console; but if we need to write it out to a certein file instead of console, we can use the following sentence:
log4j.appender.stdout=org.apache.log4j.RollingFileAppender
log4j.appender.stdout.File= filepath

For example, it can be something like this:

# ----------------------log4j.properties -----------------------------------------#
# The root logger is assigned priority level infor and it's appender is fileout;
log4j.rootLogger = INFO, fileout

# fileout
log4j.appender.file out=org.apache.log4j.RollingFileAppender
log4j.appender.fileout.File=output.log
log4j.appender.fileout.MaxFileSize=100KB
log4j.appender.fileout.MaxBackupIndex=1
log4j.appender.fileout.layout=org.apache.log4j.PatternLayout
log4j.appender.fileout.layout.ConversionPattern=%-d{yyyy-MM-dd HH:mm:ss} [%c]-[%p] %m%n

# limit categories
log4j.logger.com.tt.netcomp = INFO

# --------------------Over----------------------------#

In addition, different package can be set to different limit level. For example,

# limit categories
log4j.logger.com.tt.netcomp. domain = DEBUG
log4j.logger.com.tt.netcomp. service = WARN

In this case, domain package will have the limit level as debug while service package as warn. The other package are set to be info as default since we assign the rootLogger level as INFO in the root setting area.

No comments: