SoFunction
Updated on 2025-04-22

Spring Boot integrated log4j2 log configuration detailed tutorial

Preface

When the project is progressing, if the first thing is to build a Spring framework, then the second thing is to build a log framework based on Sring. This article is a summary of the blogger's integration of Log4j2 logs when using Spring Boot to build a project during the learning process

1. Common logging frameworks

  • : It is the Java native logging framework introduced by JDK in version 1.4
  • Log4j: An open source project of Apache that can control the destination of log information transfer is console, files, GUI components, etc.
  • LogBack: is an improved version of Log4j
  • Log4j2: Log4j2 is no longer just an upgraded version of Log4j, it has been rewritten from beginning to end

2. Introduction to configuration parameters

1. Log level

There are 8 levels in total, from low to high: All < Trace < Debug < Info < Warn < Error < Fatal < OFF

mechanism: If the level of a log information is greater than or equal to the level of the configuration file, record it

  • All: The lowest level is used to open all logging
  • Trace: Tracing means to advance the program, you can write a trace output
  • Debug: Debugging, pointing out fine-grained information events, is very helpful for debugging applications.
  • Info: Message highlights the operation process of the application at a coarse-grained level
  • Warn: Output warnings and logs at the following levels of warning. Some information is not error information, but you should also give the programmer some prompts.
  • Error: Output error message log
  • Fatal: Output logs for each critical error that will cause the application to exit
  • OFF: The highest level, used to turn off all logging

2. Output form

  • CONSOLE (output to console)
  • FILE (output to file)

3. Log format

  • SimpleLayout: Displayed in simple form
  • HTMLLayout: Displayed as HTML table
  • PatternLayout: Custom display

3.1 PatternLayout Custom log layout

The Console node, File node, and child node of the RollingFile node, specify the output format, and the default is not set to: %m%n

property:

  • pattern: Specify log format

Custom log format:

%d{yyyy-MM-dd HH:mm:ss, SSS}: Log production time, output to milliseconds
%-5level: Output log level, -5 means left alignment and fixed output of 5 characters. If it is insufficient, add 0 on the right.
%p: Log output format
%c: The name of the logger (%logger)
%m: log content, i.e. ("message")
%n: newline character
%C: Java class name (%F)
%L: Number of rows where the log output is located
%M: The method name where the log output is located
%l: The number of lines in which the output statement is located, including class name, method name, file name, and line number
%t: represents the thread name (%thread)
hostName: local machine name
hostAddress: local IP address

3. Log4j2 configuration details

1. Root node Configuration

The root node has two attributes and two child nodes

property:

  • status: used to specify the level of the log print log of log4j itself
  • monitorinterval: used to specify the monitoring interval time of log4j automatic reconfiguration, unit: s, minimum is 5s

Child nodes:

  • Appenders
  • Loggers (Suggests that multiple Appenders and Loggers can be defined)

2. Appenders node

Configuration The root node child node, there are three common child nodes: Console, File, and RollingFile

2.1 Console node

The child node of the Appenders node is used to define the Appender output to the console

property:

  • name: Used to specify the name of the Appender
  • target: Optional value SYSTEM_OUT or SYSTEM_ERR. Generally, only default is set: SYSTEM_OUT

Child nodes:

  • PatternLayout: Output format, default value: %m%n

2.2 File nodes

The child node of the Appenders node is used to define the Appender that outputs to the file at the specified location, and is generally used to test the output.

property:

  • name: Used to specify the name of the Appender
  • fileName: Specify the file name with full path to the destination file of the output log.

Child nodes:

  • PatternLayout: Output format, default value: %m%n
  • ThresholdFilter: Specify the output level

2.3 RollingFile node

The child node of the Appenders node is used to define the size exceeding the specified size, automatically delete the old and create a new Appender.

property:

  • name: Used to specify the name of the Appender
  • fileName: Specify the file name with full path to the destination file of the output log.
  • filePattern: Specify the name format of the newly created log file

Child nodes:

  • ThresholdFilter: Determines whether log events can be output
  • PatternLayout: Output format, default value: %m%n
  • Policies: Specify the policy of scrolling logs, which is when to create a new log file to output logs
  • DefaultRolloverStrategy: Used to specify how many log files are at most in the same folder, start deleting the oldest and creating new log files (through the max attribute)

2.3.1 ThresholdFilter node

The child node of the RollingFile node determines whether the log event can be output. There are three values ​​for the filtering condition: ACCEPT (accept), DENY (reject) or NEUTRAL (neutral)

property:

  • level: Specify the level of filtering logs
  • onMatch: The default value is NEUTRAL
  • onMismatch: The default value is DENY

2.3.2 Policies node

RollingFile node child node, specify the policy for scrolling logs

Child nodes:

  • TimeBasedTriggeringPolicy: Time-based scrolling policy, the interval attribute is used to specify how often to scroll, the default is 1hour. modulate = true Used to adjust the time
  • SizeBasedTriggeringPolicy: Based on the scrolling policy of the specified file size, the size attribute is used to define the size of each log file.

2.3.3 ThresholdFilter node

3. Loggers node

Configuration The child node of the root node

Child nodes:

  • Root: Used to specify the root log of the project. If the Logger is not specified separately, the Root log output will be used by default.
  • Logger: used to specify the form of logging separately, such as specifying different log levels for the class under the specified package, etc.

3.1 Root node

Loggers node child node

property:

  • level: Specify the log output level

Child nodes:

  • appender-ref: used to specify which Appender the log is output to, and specify it through ref

3.2 Logger node

property:

  • level: Specify the log output level
  • name: used to specify the full package path of the class or class to which the Logger is applicable, inherited from the Root node

Child nodes:

  • appender-ref: used to specify which Appender the log is output to, and specify it through ref

4. Log4j2 usage steps

1. Add dependencies

Spring Boot uses logback's log framework by default, so logback needs to be excluded, otherwise an error will occur due to jar dependency conflict.

&lt;!-- web --&gt;
&lt;dependency&gt;
    &lt;groupId&gt;&lt;/groupId&gt;
    &lt;artifactId&gt;spring-boot-starter-web&lt;/artifactId&gt;
    &lt;!--RemoveSpringBootDefault configuration--&gt;
    &lt;exclusions&gt;
        &lt;!--The default filter systemlogbacklog--&gt;
        &lt;exclusion&gt;
            &lt;groupId&gt;&lt;/groupId&gt;
            &lt;artifactId&gt;spring-boot-starter-logging&lt;/artifactId&gt;
        &lt;/exclusion&gt;
    &lt;/exclusions&gt;
&lt;/dependency&gt;

&lt;!-- Log4j2 --&gt;
&lt;dependency&gt;
    &lt;groupId&gt;&lt;/groupId&gt;
    &lt;artifactId&gt;spring-boot-starter-log4j2&lt;/artifactId&gt;
&lt;/dependency&gt;

2. Configuration

Create a new file under resources and write the following content:

&lt;?xml version="1.0" encoding="UTF-8"?&gt;

&lt;!--ConfigurationThe one behindstatus,This is for setting uplog4j2The output of the information within itself,Can not be set,When set totracehour,You'll seelog4j2Various internal detailed outputs--&gt;
&lt;!--monitorInterval: Log4jAble to automatically detect and modify configurations Files and reconfigurations themselves,Set the interval seconds--&gt;
&lt;configuration monitorInterval="5"&gt;
    &lt;!--Log level and priority sorting: OFF &gt; FATAL &gt; ERROR &gt; WARN &gt; INFO &gt; DEBUG &gt; TRACE &gt; ALL --&gt;

    &lt;!-- Set properties yourself,Pass later${}Come and visit --&gt;
    &lt;properties&gt;
        &lt;!--Log storage directory--&gt;
        &lt;property name="LOG_HOME"&gt;log4j2-logs&lt;/property&gt;
        &lt;!--Log Name--&gt;
        &lt;property name="LOG_NAME"&gt;patrick-blog-server&lt;/property&gt;
        &lt;!--Log format-document--&gt;
        &lt;property name="LOG_FORMAT"&gt;[%d{yyyy-MM-dd HH:mm:}] %p %t %c[%L] - %m %n&lt;/property&gt;
        &lt;!--Log format-Console--&gt;
        &lt;property name="LOG_FORMAT_CONSOLE"&gt;%d{yyyy-MM-dd HH:mm:} %highlight{%-5level} [%t] %highlight{%c{1.}.%M(%L)}: %msg%n%throwable&lt;/property&gt;
        &lt;!--Backup directory- 根据年月建立document夹 --&gt;
        &lt;property name="BACKUP_HOME"&gt;${LOG_HOME}/$${date:yyyy-MM}&lt;/property&gt;
        &lt;!--Backup frequency--&gt;
        &lt;property name="BACK_HZ"&gt;%d{yyyy-MM-dd}&lt;/property&gt;
    &lt;/properties&gt;

    &lt;appenders&gt;
        &lt;!--Console日志--&gt;
        &lt;console name="console" target="SYSTEM_OUT"&gt;
            &lt;!--Format of output log--&gt;
            &lt;PatternLayout pattern="${LOG_FORMAT_CONSOLE}" disableAnsi="false" noConsoleNoAnsi="false"/&gt;
            &lt;!--Console只输出levelInformation at or above levels(onMatch),Others are directly rejected(onMismatch)--&gt;
            &lt;ThresholdFilter level="info" onMatch="ACCEPT" onMismatch="DENY"/&gt;
        &lt;/console&gt;

        &lt;!--document会打印出所有information,thislogThe program will be automatically cleared every time you run it,Depend onappendAttribute determination,适合临hour测试用--&gt;
        &lt;File name="filelog" fileName="${LOG_HOME}/${LOG_NAME}/" append="false"&gt;
            &lt;PatternLayout pattern="${LOG_FORMAT}"/&gt;
        &lt;/File&gt;

        &lt;!-- this会打印出所有ofinfoInformation at the following levels,Each time the size exceedssize,Then thissizeLogs of size will be automatically saved by year-月份建立ofdocument夹下面并进行压缩,As an archive--&gt;
        &lt;RollingFile name="infoLog" fileName="${LOG_HOME}/${LOG_NAME}/" filePattern="${LOG_HOME}/${LOG_NAME}-INFO-%d{yyyy-MM-dd}_%"&gt;
            &lt;!--Console只输出levelInformation at or above level(onMatch),Others are directly rejected(onMismatch)--&gt;
            &lt;ThresholdFilter level="info" onMatch="ACCEPT" onMismatch="DENY"/&gt;
            &lt;PatternLayout pattern="${LOG_FORMAT}"/&gt;
            &lt;Policies&gt;
                &lt;!--intervalThe attribute is used to specify how often to scroll,The default is1 hour--&gt;
                &lt;TimeBasedTriggeringPolicy interval="1"/&gt;
                &lt;SizeBasedTriggeringPolicy size="10MB"/&gt;
            &lt;/Policies&gt;
            &lt;!-- DefaultRolloverStrategyIf the property is not set,则默认为最多同一document夹下7个document开始覆盖--&gt;
            &lt;DefaultRolloverStrategy max="15"/&gt;
        &lt;/RollingFile&gt;

        &lt;!-- this会打印出所有ofwarnInformation at the following levels,Each time the size exceedssize,Then thissizeLogs of size will be automatically saved by year-月份建立ofdocument夹下面并进行压缩,As an archive--&gt;
        &lt;RollingFile name="warnLog" fileName="${LOG_HOME}/${LOG_NAME}/" filePattern="${LOG_HOME}/${LOG_NAME}-WARN-%d{yyyy-MM-dd}_%"&gt;
            &lt;!--Console只输出levelInformation at or above level(onMatch),Others are directly rejected(onMismatch)--&gt;
            &lt;ThresholdFilter level="warn" onMatch="ACCEPT" onMismatch="DENY"/&gt;
            &lt;PatternLayout pattern="${LOG_FORMAT}"/&gt;
            &lt;Policies&gt;
                &lt;!--intervalThe attribute is used to specify how often to scroll,The default is1 hour--&gt;
                &lt;TimeBasedTriggeringPolicy interval="1"/&gt;
                &lt;SizeBasedTriggeringPolicy size="10MB"/&gt;
            &lt;/Policies&gt;
            &lt;!-- DefaultRolloverStrategyIf the property is not set,则默认为最多同一document夹下7个document开始覆盖--&gt;
            &lt;DefaultRolloverStrategy max="15"/&gt;
        &lt;/RollingFile&gt;

        &lt;!-- this会打印出所有oferrorInformation at the following levels,Each time the size exceedssize,Then thissizeLogs of size will be automatically saved by year-月份建立ofdocument夹下面并进行压缩,As an archive--&gt;
        &lt;RollingFile name="errorLog" fileName="${LOG_HOME}/${LOG_NAME}/" filePattern="${LOG_HOME}/${LOG_NAME}-ERROR-%d{yyyy-MM-dd}_%"&gt;
            &lt;!--Console只输出levelInformation at or above level(onMatch),Others are directly rejected(onMismatch)--&gt;
            &lt;ThresholdFilter level="error" onMatch="ACCEPT" onMismatch="DENY"/&gt;
            &lt;PatternLayout pattern="${LOG_FORMAT}"/&gt;
            &lt;Policies&gt;
                &lt;!--intervalThe attribute is used to specify how often to scroll,The default is1 hour--&gt;
                &lt;TimeBasedTriggeringPolicy interval="1"/&gt;
                &lt;SizeBasedTriggeringPolicy size="10MB"/&gt;
            &lt;/Policies&gt;
            &lt;!-- DefaultRolloverStrategyIf the property is not set,则默认为最多同一document夹下7个document开始覆盖--&gt;
            &lt;DefaultRolloverStrategy max="15"/&gt;
        &lt;/RollingFile&gt;

    &lt;/appenders&gt;

    &lt;!--LoggerThe form used by nodes to specify the log separately,For example, you need to subscribe for the specified packageclassSpecify different log levels, etc.。--&gt;
    &lt;!--Then defineloggers,Only definedloggerand introducedappender,appenderIt will take effect--&gt;
    &lt;loggers&gt;

        &lt;!--Filter outspringandmybatisSome uselessDEBUGinformation--&gt;
        &lt;logger name="" level="info" additivity="false"&gt;
            &lt;AppenderRef ref="console"/&gt;
        &lt;/logger&gt;
        &lt;!--监控系统information--&gt;
        &lt;!--ifadditivitySet asfalse,ZeziLogger Only in your ownappenderOutput,Not in the fatherLogger ofappenderOutput。--&gt;
        &lt;Logger name="" level="info" additivity="false"&gt;
            &lt;AppenderRef ref="console"/&gt;
        &lt;/Logger&gt;

        &lt;root level="info"&gt;
            &lt;!-- 输出到Console --&gt;
            &lt;appender-ref ref="console"/&gt;
            &lt;!-- 输出到document --&gt;
            &lt;appender-ref ref="filelog"/&gt;
            &lt;appender-ref ref="infoLog"/&gt;
            &lt;appender-ref ref="warnLog"/&gt;
            &lt;appender-ref ref="errorLog"/&gt;
        &lt;/root&gt;
    &lt;/loggers&gt;

&lt;/configuration&gt;

3. Use the lombok tool to simplify creating Logger classes

Using lombok can omit the process of building logger instances and simplify development with @Slf4j annotation

@Slf4j
public class LogTest {
  
  public static void main(String... args) {
    ("Something is warning here");
  }
  
}

Summarize

This is the article about Spring Boot integrating log4j2 log configuration. For more related Spring Boot integrating log4j2 log configuration content, please search for my previous article or continue browsing the related articles below. I hope everyone will support me in the future!