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 "http://logging.apache.org/log4j/docs/api/org/apache/log4j/xml/log4j.dtd">
<log4j:configuration xmlns:log4j="http://jakarta.apache.org/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" />
</layout>

</appender>
<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"/>
</layout>
</appender>


<!-- the root category -->

<root>
<!-- 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"/>
</root>

</log4j:configuration>

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!");

http://logging.apache.org/

No comments: