Thursday, June 26, 2008

Apache Logging - log4j Configuration

Add the log4j.xml file to the classpath:
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE log4j:configuration PUBLIC "">
<log4j:configuration xmlns:log4j="">

<!-- an appender is an output destination, such as e.g. the console or a file;
names of appenders are arbitrarily chosen -->
<appender name="stdout" class="org.apache.log4j.ConsoleAppender">
<!-- layouts are used by appenders to format layout -->
<layout class="org.apache.log4j.PatternLayout">
<param name="ConversionPattern"

value="%d{ABSOLUTE} %5p %c{1}:%L - %m%n" />

<appender name="debug" class="org.apache.log4j.FileAppender">
<param name="File" value="logs/debug.log" />
<param name="Threshold" value="debug" />
<layout class="org.apache.log4j.PatternLayout">
<param name="ConversionPattern"
value="%d{ISO8601} %-5p %c - %m%n"/>

<!-- the root category -->

<!-- all|debug|info|warn|error|fatal|off|null -->
<!-- all log messages of level debug or more serious will be logged, unless defined otherwise -->
<priority value="debug" />
<appender-ref ref="stdout" />
<appender-ref ref="debug"/>


Lazy load the logger:
* @return the log.
protected Log getLog() {
if (this.log == null) {
this.log = LogFactory.getLog(this.getClass());
return this.log;

Use the logger:
        if (getLog().isInfoEnabled())
getLog().info("Hello World!");

No comments: