30. Java Foundation - Log4j2 Configuration and Use

Keywords: Programming xml log4j Attribute JSON

log4j2 configuration

1. The name of the configuration file and its location in the project

log4j 2.x version no longer supports file configurations like. properties suffix in 1.x. The suffix name of the 2.x version configuration file can only be ". xml", "json" or ". jsn".

The priority of system selection profile (from first to last) is as follows:

  • (1) A file named log4j2-test.json or log4j2-test.jsn under the classpath.
  • (2) The file named log4j2-test.xml under classpath.
  • (3) Files named log4j2.json or log4j2.jsn under classpath.
  • (4) A file named log4j2.xml under classpath.

We usually use log4j2. XML for naming by default. If you want to test locally, you can put log4j2-test.xml into the classpath, whereas the formal environment uses log4j2.xml, you can pack the deployment without packing log4j2-test.xml.

2. Default configuration

<?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. Configuration file node parsing

(1) Configuration of the root node

  • Attributes:

    • status: Used to specify the level of print logs for log4j itself
    • monitorinterval: Used to specify the detection interval for automatic reconfiguration of log4j, in s, with a minimum value of 5s
  • Nodes:

    • Appenders nodes, the common sub-nodes are Console, Rolling File, File
      • Console: Used to define the Appender that is exported to the console.
        • Name: Specify the name of Appender
        • target: SYSTEM_OUT or SYSTEM_ERR, which is usually set by default only: SYSTEM_OUT
        • PatternLayout: Output format, no default:% m%n.
      • File: Appender used to define files exported to a specified location
        • Name: Specify the name of Appender
        • fileName: Specifies the destination file for the output log, with the full path file name
        • PatternLayout: Output format, no default:% m%n.
      • RollingFile: Used to define new Appender s that automatically delete old ones beyond the specified size
        • Name: Specify the name of Appender
        • fileName: Specifies the destination file for the output log, with the full path file name
        • PatternLayout: Output format, no default:% m%n.
        • filePattern: Specifies the name format of the newly created log file
        • Policies: Specifies the strategy for scrolling logs, which is when a new log file is exported to the log
        • TimeBasedTriggering Policy: Policies child node, time-based scrolling strategy, interval attribute is used to specify how often to scroll, default is 1 hour. Module = true is used to adjust the time. For example, it's 3am in the morning, interval is 4, then the first roll is 4am, followed by 8am, 12am... Not 7am.
        • SizeBasedTriggering Policy: Policies child node. Based on the scrolling strategy of the specified file size, the size attribute is used to define the size of each log file.
        • Default Rollover Strategy: Used to specify a maximum of several log files in the same folder when starting to delete the oldest and create a new (through the max attribute).
    • Loggers nodes, commonly Root and Logger
      • Root: Used to specify the root log of the project. If Logger is not specified separately, the Root log output is used by default.
        • Level: Log output level, a total of eight levels, from low to high: All < Trace < Debug < Info < Warn < Error < Fatal < OFF
        • AppenderRef: Root's child node, which specifies that the log is exported to that Appender
      • Logger nodes are used to specify the form of the log separately, such as specifying different log levels for the class under the specified package.
        • Level: Log output level, a total of eight levels, from low to high: All < Trace < Debug < Info < Warn < Error < Fatal < OFF.
        • name: Used to specify the package full path of the class or class to which the Logger applies, inherited from the Root node.
        • AppenderRef: A child node of Logger that specifies which Appender the log is exported to, and if not specified, it will inherit from Root by default. If specified, it will be output in both the Appender and Root specified. At this point, we can set the additivity="false" of Logger to enter only in the custom Appender. Line output.
    • Log level.
      • There are eight levels, from low to high: All < Trace < Debug < Info < Warn < Error < Fatal < OFF.
        • All: Minimum level, used to open all log records.
        • Trace: It's tracing. If the program advances below, you can write a trace output, so traces should be a lot, but that's OK. We can set the lowest log level to keep him from output.
        • Debug: Fine-grained information events are very helpful for debugging applications.
        • Info: Messages highlight the running process of the application at the coarse-grained level.
        • Warn: Output warning and log below warn level.
        • Error: Output error message log.
        • Fatal: Output every serious error event that will cause the application to exit the log.
        • OFF: The highest level used to close all log records.

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

(2) More complete configuration template

<?xml version="1.0" encoding="UTF-8"?>
<!--Log Level and Priority Sorting: OFF > FATAL > ERROR > WARN > INFO > DEBUG > TRACE > ALL -->
<!--Configuration Hinder status,This is used for settings log4j2 The internal information output can not be set when it is set to trace When you see log4j2 Various internal detailed outputs-->
<!--monitorInterval: Log4j Ability to automatically detect modifications to configuration files and reconfiguration itself, setting intervals of seconds-->
<configuration status="WARN" monitorInterval="30">
    <!--Define all 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 Every time the program runs, it will be cleared automatically. append Attribute determination, 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 them. info Information at or below the level, each size exceeding size,Then this size Size logs are automatically saved by year-Folder created in January 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 Information at and above levels( 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 Property is not set, default is up to the same folder7Five files, set up here20 -->
            <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 Only then will it take effect-->
    <loggers>
        <!--Filtration 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>

Posted by HostingTrade on Wed, 31 Jul 2019 22:43:57 -0700