Middle
What are the ways to configure log4j?
sobes.tech AI
Answer from AI
log4j can be configured in one of the following ways:
-
Programmatically: Configuration is set directly in Java code.
// Example of programmatic configuration org.apache.log4j.BasicConfigurator.configure(); org.apache.log4j.Logger rootLogger = org.apache.log4j.Logger.getRootLogger(); rootLogger.setLevel(org.apache.log4j.Level.DEBUG); org.apache.log4j.ConsoleAppender consoleAppender = new org.apache.log4j.ConsoleAppender( new org.apache.log4j.PatternLayout("%d [%t] %-5p %c - %m%n") ); rootLogger.addAppender(consoleAppender); org.apache.log4j.Logger logger = org.apache.log4j.Logger.getLogger(MyClass.class); logger.debug("Debug message"); -
Using a properties file: Configuration is specified in a
.propertiesfile. Log4j automatically searches for a file namedlog4j.propertiesin the classpath.# Example of log4j.properties file log4j.rootLogger=DEBUG, console, file # Console appender configuration log4j.appender.console=org.apache.log4j.ConsoleAppender log4j.appender.console.layout=org.apache.log4j.PatternLayout log4j.appender.console.layout.ConversionPattern=%d [%t] %-5p %c - %m%n # File appender configuration log4j.appender.file=org.apache.log4j.FileAppender log4j.appender.file.File=application.log log4j.appender.file.Append=true log4j.appender.file.layout=org.apache.log4j.PatternLayout log4j.appender.file.layout.ConversionPattern=%d [%t] %-5p %c - %m%n -
Using an XML file: Configuration is specified in a
.xmlfile. Log4j can automatically find alog4j.xmlfile in the classpath.<!-- Example of log4j.xml file --> <!DOCTYPE log4j:configuration PUBLIC "-//APACHE//DTD LOG4J 1.2//EN" "log4j.dtd"> <log4j:configuration xmlns:log4j="http://jakarta.apache.org/log4j/"> <appender name="console" class="org.apache.log4j.ConsoleAppender"> <layout class="org.apache.log4j.PatternLayout"> <param name="ConversionPattern" value="%d [%t] %-5p %c - %m%n"/> </layout> </appender> <appender name="file" class="org.apache.log4j.FileAppender"> <param name="File" value="application.log"/> <param name="Append" value="true"/> <layout class="org.apache.log4j.PatternLayout"> <param name="ConversionPattern" value="%d [%t] %-5p %c - %m%n"/> </layout> </appender> <root> <level value="DEBUG"/> <appender-ref ref="console"/> <appender-ref ref="file"/> </root> </log4j:configuration>
Loading order of configuration (by default):
Log4j searches for configuration files in the following order:
- System property
log4j.configuration(specifies the path to the configuration file). log4j.xmlfile in the classpath.log4j.propertiesfile in the classpath.- If no file is found, a default configuration is used (
ConsoleAppenderwithERRORlevel).
Configuration priority:
- Programmatic configuration has the highest priority.
- Then comes configuration specified via the system property.
- XML file has higher priority than the properties file if both are present and no system property is specified.