A diagram shows you how log4j2 works
-
Environment to prepare
- Log4j – API – 2.3. The jar
- Log4j – core – 2.3. The jar
- Log4j-web-2.3. jar (a jar package that needs to be introduced in a Web project. This is the initialization of the data.)
-
Data initialization
We know that the entry to the Web project is in web.xml. So we need to add log4j’s listeners and filters
<listener> <listener-class>org.apache.logging.log4j.web.Log4jServletContextListener</listener-class> </listener> <filter> <filter-name>log4jServletFilter</filter-name> <filter-class>org.apache.logging.log4j.web.Log4jServletFilter</filter-class> </filter> <filter-mapping> <filter-name>log4jServletFilter</filter-name> <url-pattern>/*</url-pattern> <dispatcher>REQUEST</dispatcher> <dispatcher>FORWARD</dispatcher> <dispatcher>INCLUDE</dispatcher> <dispatcher>ERROR</dispatcher> </filter-mapping>Copy the code
At this point we have log4j configured successfully. However, it is possible to find that the above listeners and filters are not present in real development. There is no research reason due to time problems. Log4j has a default configuration in the source code. We did not specify the location of the configuration file above, log4j will read the default configuration in the JAR. The default configuration files in the system are as follows:
- Json or log4j2-test. JSN in the classpath.
- Log4j2-test.xml file in classpath.
- The file log4j2.json or log4j2. JSN is in the classpath.
- File log4j2.xml in classpath.
-
Log4j2 Configuration details
-
The logger hierarchy
- There are eight levels in ascending order: All < Trace < Debug < Info < Warn < Error < Fatal < OFF.
- All: indicates the lowest level. It is used to enable All logging.
- Trace: it’s Trace, it’s Trace, it’s Trace, it’s Trace, it’s Trace, it’s Trace, it’s Trace, it’s Trace, it’s Trace, it’s Trace, it’s Trace, it’s Trace, it’s Trace.
- Debug: Indicates fine-grained information events that are very helpful for debugging applications.
- Info: Messages highlight the execution of the application at a coarse-grained level.
- Warn: Logs of warning and lower levels are generated.
- Error: Logs of Error information are output.
- Fatal: logs every critical error event that will cause the application to exit.
- OFF: indicates the highest level. It is used to disable all logging.
-
For example,
We have configured many loggers as above. Each Logger has its own name. In our code, such use ` private static final Logger bossRequestTeletextLogger. = that the LogManager getLogger ("bossRequestTeletextLogger"); BossRequestTeletxtLogger will use our last Logger, which has an INFO level. Storage is' teletextLoggerFile 'stored in a file.Copy the code