Log4j2 configuration file log4j2.xml

1. Background

Recently, due to the needs of the project, we have migrated all versions of log4j 1.x to the version of log4j 2.x, and the subsequent slf4j integration log4j configuration (the perfect solution for building a project log system using Slf4j integration Log4j2) and log4j2 configuration file details require a good chat.This article is dedicated to explaining the significance of the various tags in the log4j2.xml configuration file.

2. Configuration Full Solution

1. About the name of the configuration file and where to store it in the project

The log4j 2.x version no longer supports file configurations such as the.properties suffix in 1.x. Version 2.x configuration file suffix names can only be'.xml','.json'or'.jsn'.

Priority (first to last) for system selection of profiles is as follows:

(1) A file named log4j2-test.json or log4j2-test.jsn under the classpath.

(2) A file named log4j2-test.xml under the classpath.

(3) A file named log4j2.json or log4j2.jsn under classpath.

(4) File named log4j2.xml under classpath.

In general, we use log4j2.xml for naming by default.If you want to test locally, you can place log4j2-test.xml in the classpath, whereas the formal environment uses log4j2.xml, you can package your deployment without packaging log4j2-test.xml.

2. Default default profile

<?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} - %msg%n"/>
    </Console>
  </Appenders>
  <Loggers>
    <Root level="error">
      <AppenderRef ref="Console"/>
    </Root>
  </Loggers>
</Configuration>

3. Profile Node Resolution

(1). The root node Configuration has two attributes: status and monitorinterval, and two child nodes: Appenders and Loggers (indicating that multiple Appenders and Loggers can be defined).

status is used to specify the level of the log4j's own print log.

monitorinterval is used to specify the monitoring interval for automatic reconfiguration of log4j in s and a minimum of 5s.

(2).Appenders node, there are three common seed nodes: Console, RollingFile, File.

The Console node defines the Appender that is output to the console.

Name: Specify the name of the Appender.

target:SYSTEM_OUT or SYSTEM_ERR, generally set default only: SYSTEM_OUT.

PatternLayout: Output format, not set to default:%m%n.

The File node defines the Appender of the file output to the specified location.

Name: Specify the name of the Appender.

fileName: Specifies the file name of the destination file with full path for the output log.

PatternLayout: Output format, not set to default:%m%n.

The RollingFile node is used to define a new Appender that automatically deletes the old one beyond the specified size.

Name: Specify the name of the Appender.

fileName: Specifies the file name of the destination file with full path for the output log.

PatternLayout: Output format, not set to default:%m%n.

filePattern: Specify the name format for the new log file.

Policies: Specifies the strategy for scrolling logs, which is when to create a new log file output log.

TimeBasedTriggeringPolicy:Policies subnode, time-based scrolling policy, interval property to specify how often to scroll, default is 1 hour.Module=true is used to adjust the time: for example, it is 3am in the morning, interval is 4, then the first roll is 4am, followed by 8am, 12am... instead of 7am.

SizeBasedTriggeringPolicy:Policies subnode, the size property defines the size of each log file based on the scrolling policy for the specified file size.

DefaultRolloverStrategy: Used to specify a maximum number of log files in the same folder and start deleting the oldest and creating a new one (via the max attribute).

(3). There are two common types of Loggers nodes: Root and Logger.

Root node is used to specify the root log of the project. If a Logger is not specified separately, the Root log output will be used by default

Level: The log output level has eight levels, ranging from low to high: All < Trace < Debug < Info < Warn < Error < Fatal < OFF.

The child node of AppenderRef:Root, which specifies to which Appender the log is exported.

The Logger node is used to specify the form of the log separately, such as specifying different log levels for the class es under the specified package.

Level: The log output level has eight levels, ranging from low to high: All < Trace < Debug < Info < Warn < Error < Fatal < OFF.

name: Used to specify the full path of the class or package where the Logger applies, inheriting from the Root node.

Child node of AppenderRef:Logger, which specifies to which Appender the log is exported, and if not specified, it will inherit from Root by default. If specified, it will be output in both the specified Appender and Root Appenders, at which point we can set Logger additivity="false" onlyOutput in a custom Appender.

(4). About log level.

There are eight levels, from low to high: All < Trace < Debug < Info < Warn < Error < Fatal < OFF.

All: The lowest level for opening all log records.

Trace: Trace means that if the program advances below, you can write a trace output, so there should be a lot of traces, but that's OK. We can set the minimum log level to keep him from outputting.

Debug: Indicating fine-grained information events is very helpful for debugging applications.

Info: Messages emphasize the running process of the application at a coarse-grained level.

Warn: Output warnings and logs below warn level.

Error: Output error message log.

Fatal: Output a log of every serious error event that will cause the application to exit.

OFF: The highest level used to turn off all logging.

The program prints logs above or equal to the level set. The higher the level set, the fewer logs will be printed.

4. More complete log4j2.xml configuration template

<?xml version="1.0" encoding="UTF-8"?>
<!--Log level and priority ordering: OFF > FATAL > ERROR > WARN > INFO > DEBUG > TRACE > ALL -->
<!--Configuration Hinder status,This is for setting up log4j2 Internal information output can be set when set to trace When you do, you will see log4j2 Various internal verbose outputs-->
<!--monitorInterval: Log4j Ability to automatically detect modifications to profile and reconfiguration itself, set interval seconds-->
<configuration status="WARN" monitorInterval="30">
    <!--Define all first appender-->
    <appenders>
    <!--Configuration of this output console-->
        <console name="Console" target="SYSTEM_OUT">
        <!--Format of output log-->
            <PatternLayout pattern="[%d{HH:mm:ss:SSS}] [%p] - %l - %m%n"/>
        </console>
    <!--The file prints out all the information. This log Each time the program is run, it is automatically emptied by append Property decision, which is also useful for temporary testing-->
    <File name="log" fileName="log/test.log" append="false">
       <PatternLayout pattern="%d{HH:mm:ss.SSS} %-5level %class{36} %L %M - %msg%xEx%n"/>
    </File>
    <!-- This will print out all of the info And below, each time larger than size,Then this size Size logs are automatically saved by year-Folder created in month and compressed for archiving-->
        <RollingFile name="RollingFileInfo" fileName="${sys:user.home}/logs/info.log"
                     filePattern="${sys:user.home}/logs/$${date:yyyy-MM}/info-%d{yyyy-MM-dd}-%i.log">
            <!--Console Output Only level And above ( onMatch),Other direct rejections ( onMismatch)-->        
            <ThresholdFilter level="info" onMatch="ACCEPT" onMismatch="DENY"/>
            <PatternLayout pattern="[%d{HH:mm:ss:SSS}] [%p] - %l - %m%n"/>
            <Policies>
                <TimeBasedTriggeringPolicy/>
                <SizeBasedTriggeringPolicy size="100 MB"/>
            </Policies>
        </RollingFile>
        <RollingFile name="RollingFileWarn" fileName="${sys:user.home}/logs/warn.log"
                     filePattern="${sys:user.home}/logs/$${date:yyyy-MM}/warn-%d{yyyy-MM-dd}-%i.log">
            <ThresholdFilter level="warn" onMatch="ACCEPT" onMismatch="DENY"/>
            <PatternLayout pattern="[%d{HH:mm:ss:SSS}] [%p] - %l - %m%n"/>
            <Policies>
                <TimeBasedTriggeringPolicy/>
                <SizeBasedTriggeringPolicy size="100 MB"/>
            </Policies>
        <!-- DefaultRolloverStrategy If the property is not set, it defaults to a maximum of 7 files in the same folder, where 20 files are set -->
            <DefaultRolloverStrategy max="20"/>
        </RollingFile>
        <RollingFile name="RollingFileError" fileName="${sys:user.home}/logs/error.log"
                     filePattern="${sys:user.home}/logs/$${date:yyyy-MM}/error-%d{yyyy-MM-dd}-%i.log">
            <ThresholdFilter level="error" onMatch="ACCEPT" onMismatch="DENY"/>
            <PatternLayout pattern="[%d{HH:mm:ss:SSS}] [%p] - %l - %m%n"/>
            <Policies>
                <TimeBasedTriggeringPolicy/>
                <SizeBasedTriggeringPolicy size="100 MB"/>
            </Policies>
        </RollingFile>
    </appenders>
    <!--Then define logger,Only defined logger And introduced appender,appender Will take effect-->
    <loggers>
        <!--Filter out spring and mybatis Some useless DEBUG information-->
        <logger name="org.springframework" level="INFO"></logger>
        <logger name="org.mybatis" level="INFO"></logger>
        <root level="all">
            <appender-ref ref="Console"/>
            <appender-ref ref="RollingFileInfo"/>
            <appender-ref ref="RollingFileWarn"/>
            <appender-ref ref="RollingFileError"/>
        </root>
    </loggers>
</configuration>

Keywords: Programming xml log4j JSON encoding

Added by reethu on Tue, 03 Sep 2019 04:49:48 +0300