1. configuration: http://logging.apache.org/log4j/2.x/manual/configuration.html
When Log4j starts it will locate all the ConfigurationFactory plugins and arrange then in weighted order from highest to lowest. As delivered, Log4j contains two ConfigurationFactory implementations, one for JSON and one for XML.
- Log4j will inspect the "log4j.configurationFile" system property and, if set, will attempt to load the configuration using theConfigurationFactory that matches the file extension.
- If no system property is set the JSON ConfigurationFactory will look for log4j2-test.json or log4j2-test.jsn in the classpath.
- If no such file is found the XML ConfigurationFactory will look for log4j2-test.xml in the classpath.
- If a test file cannot be located the JSON ConfigurationFactory will look for log4j2.json or log4j2.jsn on the classpath.
- If a JSON file cannot be located the XML ConfigurationFactory will try to locate log4j2.xml on the classpath.
- If no configuration file could be located the DefaultConfiguration will be used. This will cause logging output to go to the console.
An example application named MyApp that uses log4j can be used to illustrate how this is done.
import com.foo.Bar;
// Import log4j classes.
import org.apache.logging.log4j.Logger;
public class MyApp {
// Define a static logger variable so that it references the
// Logger instance named "MyApp".
Logger logger = LogManager.getLogger(MyApp.class.getName());
public static void main(String[] args) {
// Set up a simple configuration that logs on the console.
logger.trace("Entering application.");
Bar bar = new Bar();
if (!bar.doIt() {
logger.error("Didn't do it.");
}
logger.trace("Exiting application."); }
}
MyApp begins by importing log4j related classes. It then defines a static logger variable with the nameMyApp which happens to be the fully qualified name of the class.
MyApp uses the Bar class defined in the packagecom.foo.
- package com.foo;
- import org.apache.logging.log4j.Logger;
- public class Bar {
- static Logger logger = LogManager.getLogger(Bar.class.getName());
- public boolean doIt() {
- logger.entry();
- logger.error("Did it again!");
- return logger.exit(false);
- }
- }
运行时:
$ java -Dlog4j.configurationFile=src/main/java/resources/log4j2.xml com.foo.Bar.MyApp
log4j2.xml
<?xml version="1.0" encoding="UTF-8"?>
<Configuration status="WARN">
<Appenders>
<Console name="Console" target="SYSTEM_OUT">
<PatternLayout pattern="%d{HH:mm:ss.SSS} [%t] %-5level %logger{36} - [example] %msg%n"/>
</Console>
</Appenders>
<Loggers>
<Root level="trace"> <!--> error, info, trace, default is error-->
<AppenderRef ref="Console"/>
</Root>
</Loggers>
</Configuration>