Slf4j is a logging specification, standard and interface developed for logging framework implementation. It cannot be used independently, but needs to be used with specific logging framework implementation. Log4j, logback, and log4j2 are three logging framework implementations respectively. Log4j2 is an improved version of log4j 1.x and logback.

The following describes the basic configuration of an XML log4j2 configuration file.

1. The XML node

Configuration

The root node.

  • Status, log4j2 Specifies the log level of the log framework. OFF > FATAL > ERROR > WARN > INFO > DEBUG > TRACE > ALL
  • MonitorInterval, interval for re-reading configuration files, in seconds

Properties

Property (optional) to define constants that are later referenced in other configuration items via ${variable name}.

Appenders

Output sources, used to define log output, include console ConsoleAppender, scroll FileAppender, RollingRandomAccessFile, and so on.

RollingRandomAccessFile

Scroll the file according to a policy.

  • Name specifies the name of the Appender
  • FileName indicates the path and name of the current log file
  • FilePattern, the rules for transferring and renaming files when scrolling occurs

ThresholdFilter

Determines whether log events can be output.

  • ACCEPT, DENY, NEUTRAL is NEUTRAL.
  • OnMatch (level and above), onMismatch (level below)

PatternLayout

The log output format, the official document: logging.apache.org/log4j/2.x/m…

  • %d, time. The default format is 2012-11-02 14:34:02,123
  • %level: log level, such as FATAL, ERROR, WARN, INFO, DEBUG, RACE
  • %thread, the name of the thread
  • %c{1.}, logger name, e.g. Loggername = org.apache.mons.foo, Result= O.A.C. Foo;
  • % MSG, log information
  • %l, location information, equivalent to %C.%M(%F:%L)
  • %C, %class, full class name
  • %M, %method, method name
  • %F, %file, file name
  • %L, %line, line number
  • % n, a newline

Policies

Scroll policy for log files.

  • TimeBasedTriggeringPolicy, and combined filePattern, date format decision unit of time, the interval decision unit time interval; Modulate whether the generated file is offset in time at 0
  • SizeBasedTriggeringPolicy, log file size rolling strategy

DefaultRolloverStrategy

Default scroll policy

  • Max: indicates the maximum number of log files to be saved

2. An example


      
<! --status, log level of log4j2 itself, OFF>FATAL>ERROR>WARN>INFO>DEBUG>TRACE>ALL-->
<! --monitorInterval, interval for re-reading configuration files, in seconds
<Configuration status="OFF" monitorInterval="30">
    <! --Properties (optional), used to define constants that are later referenced by ${variable name} in other configuration items -->
    <Properties>
        <Property name="LOG_HOME">logs</Property>
        <! --_TRACE_ID, business custom variable -->
        <property name="ALL_PATTERN">[%d][%level][%thread][%X{_TRACE_ID}][%c{1.}]- %msg -%n</property>
        <property name="ERROR_PATTERN">[%d][%level][%thread][%X{_TRACE_ID}][%c{1.}]- %msg -[%l]%n</property>
        <property name="CHARSET">UTF-8</property>
        <property name="FILE_SIZE">1GB</property>
        <property name="FILE_INDEX_MAX">30</property>
    </Properties>

    <! Appenders, output source, where log output is defined -->
    <Appenders>
        <! -- Console -->
        <Console name="CONSOLE-APPENDER" target="SYSTEM_OUT">
            <PatternLayout>
                <Pattern>${ALL_PATTERN}</Pattern>
            </PatternLayout>
        </Console>
        <! --RollingRandomAccessFile, scroll the file according to certain rules -->
        <! --name, specify the Appender name -->
        <! --fileName, path and name of the current log file -->
        <! --filePattern, file transfer and rename rules when scrolling occurs -->
        <RollingRandomAccessFile name="ALL-APPENDER"
                                 fileName="${LOG_HOME}/appName-all.log"
                                 filePattern="${LOG_HOME}/%d{yyyyMMdd}/appName-all-%d{yyyyMMdd}-%i.log.gz">
            <! PatternLayout, format of log output -->
            <PatternLayout>
                <Pattern>${ALL_PATTERN}</Pattern>
            </PatternLayout>
            <! --Policies for log file scrolling -->
            <! - TimeBasedTriggeringPolicy, and combined filePattern, date format decision unit of time, the interval decision unit time interval; Does modulate generate file with 0 offset time -->
            <! - SizeBasedTriggeringPolicy, log file size rolling strategy -- -- >
            <Policies>
                <TimeBasedTriggeringPolicy interval="1" modulate="true"/>
                <SizeBasedTriggeringPolicy size="${FILE_SIZE}"/>
            </Policies>
            <! --DefaultRolloverStrategy, default scrolling strategy, Max -- maximum number of log files saved -->
            <DefaultRolloverStrategy max="${FILE_INDEX_MAX}"/>
        </RollingRandomAccessFile>

        <RollingRandomAccessFile name="ERROR-APPENDER"
                                 fileName="${LOG_HOME}/appName-error.log"
                                 filePattern="${LOG_HOME}/%d{yyyyMMdd}/appName-error-%d{yyyyMMdd}-%i.log.gz">
            <! Filters, which determine whether the log event can be output: ACCEPT, DENY, NEUTRAL; OnMatch - this level and above, onMismatch- This level and below -->
            <ThresholdFilter level="WARN" onMatch="ACCEPT" onMismatch="DENY"/>
            <PatternLayout>
                <Pattern>${ERROR_PATTERN}</Pattern>
            </PatternLayout>
            <Policies>
                <TimeBasedTriggeringPolicy interval="1" modulate="true"/>
                <SizeBasedTriggeringPolicy size="${FILE_SIZE}"/>
            </Policies>
            <DefaultRolloverStrategy max="${FILE_INDEX_MAX}"/>
        </RollingRandomAccessFile>
    </Appenders>

    <Loggers>
        <! -- Each configuration must have a Root logger with no name attribute and no additivity.
        <! --level: log output level, from low to high: All<TRACE<DEBUG<INFO<WARN<ERROR<FATAL<OFF-->
        <! --includeLocation: stack snapshot is required to output location information, which has a significant impact on performance, so asynchronous logger disable this feature by default, can be enabled by setting true -->
        <! --AppenderRef: Specify to which Appender the log should be exported -->
        <asyncRoot level="INFO" includeLocation="true">
            <AppenderRef ref="CONSOLE-APPENDER"/>
            <AppenderRef ref="ALL-APPENDER"/>
            <AppenderRef ref="ERROR-APPENDER"/>
        </asyncRoot>
        <! --name: class to which this Logger belongs or package path to which that class belongs -->
        <! --additivity: set whether log events are output in Root Logger, false to avoid repeated output -->
        <asyncLogger name="com.xxx.xxx" level="INFO" additivity="false" includeLocation="true">
            <AppenderRef ref="CONSOLE-APPENDER"/>
            <AppenderRef ref="ALL-APPENDER"/>
            <AppenderRef ref="ERROR-APPENDER"/>
        </asyncLogger>
    </Loggers>
</Configuration>
Copy the code