Use the DOMConfigurator
to configure Log4J with an
XML document. The following code configures Log4J from a resource
named log4j.xml
, and logs two messages:
import org.apache.log4j.DOMConfigurator; import org.apache.log4j.Logger; URL log4Jresource = this.getClass( ).getResource("log4j.xml"); DOMConfigurator.configure( lof4Jresource ); Logger log = Logger.getLogger( "com.discursive.SomeApp" ); log.info( "This is a log message" ); log.error( "This is an error message" );
The log4j.xml
file contains a basic Log4J
configuration, which sets the root category logging level to
WARN
, and the application’s
logging level to DEBUG
. This XML document
configures Log4J exactly the way that Log4J was configured by the
previous example; log messages are sent to both the console and a
RollingFileAppender
:
<?xml version="1.0" encoding="UTF-8" ?> <configuration configDebug="true"> <appender name="STDOUT" class="org.apache.log4j.ConsoleAppender"> <layout class="org.apache.log4j.PatternLayout"> <param name="ConversionPattern" value="%5p (%F:%L) %m%n"/> </layout> </appender> <appender name="FILE" class="org.apache.log4j.RollingFileAppender"> <param name="File" value="output.log" /> <param name="MaxFileSize" value="2000KB" /> <param name="MaxBackupIndex" value="5" /> <layout class="org.apache.log4j.PatternLayout"> <param name="ConversionPattern" value="%d %-5p %c - %m%n"/> </layout> </appender> <category name="com.discursive"> <priority value="DEBUG" /> </category> <root> <priority value="WARN"/> <appender-ref ref="STDOUT" /> <appender-ref ref="FILE" /> </root> </configuration>
This configuration will produce the same output as the previous recipe. The only difference between this recipe and the last is that XML is used to configure Log4J.
For more information about Log4J, see the Log4J project page at http://logging.apache.org/log4.
3.145.109.8