How to customize the log output format of the SpringBoot project

The Springboot project has several logging frameworks. The default is to use the Logback logging framework, but I like to use the Log4j2 logging framework because Log4j2 has strong performance, strong scalability, customizable level, support for kafka4, and stable data

Insert picture description here
The default output log format is as shown below

Insert picture description here
The log output format after I use the log4j2 log framework is as follows

Insert picture description here
The following are the steps to use log4j2 logging framework to set the log output format

1. Add log4j2 dependency in pom.xml file and exclude spring default logback log dependency

<dependency>
	<groupId>org.springframework.boot</groupId>
	<artifactId>spring-boot-starter</artifactId>
	<!-- 排除掉默认的日志框架 -->
	<exclusions>
		<exclusion>
			<groupId>org.springframework.boot</groupId>
			<artifactId>spring-boot-starter-logging</artifactId>
		</exclusion>
	</exclusions>
</dependency>
<!-- log4j2日志 -->
<dependency>
	<groupId>org.springframework.boot</groupId>
	<artifactId>spring-boot-starter-log4j2</artifactId>
</dependency>

2. Create a log4j2-spring.xml file in the src/main/resources directory. The contents of the
Insert picture description here
log4j2-spring.xml file are as follows:

<?xml version="1.0" encoding="UTF-8"?>
<!--设置log4j2的自身log级别为warn -->
<configuration status="warn">
    <properties>
    	<!--这里配置的是日志存到文件中的路径-->
        <Property name="log_path">logs</Property>
    </properties>
    <appenders>
      <!--输出格式布局,每个转换说明符以百分号(%)开头,'%'后面的转换字符有如下:-->
            <!--
            p (level) 日志级别
            c(logger) Logger的Name
            C (class) Logger调用者的全限定类名 ***
            d (date) 日期
            highlight 高亮颜色
            l (location) 调用位置 ***
            L (line) 行号
            m (msg/message) 输出的内容
            M (methode) 调用方法 ***
            maker marker的全限定名
            n 输出平台相关的换行符,'\n' '\r\n'
            pid (processId) 进程ID
            level (p)日志级别
            r JVM启动后经过的微秒
            t (tn/thread/threadName) 线程名称
            T (tid/threadId) 线程ID
            tp (threadPriority) 线程优先级
            x (NDC) 线程Context堆栈
            -->
        <console name="Console" target="SYSTEM_OUT">
            <PatternLayout pattern="[%d{yyyy-MM-dd HH:mm:ss.SSS}][%t][%c(类):%L(行)] %m%n"/>
        </console>
        <!-- 这里配置了普通日志的格式和存入文件的路径 -->
        <!-- 如果fileName中是"../info.log",代表日志存放在和项目同级下-->
        <RollingFile name="RollingFileInfo" fileName="${log_path}/info.log"
                     filePattern="${log_path}/$${date:yyyy-MM}/info-%d{yyyy-MM-dd}-%i.log">
            <Filters>
               <ThresholdFilter level="INFO"/>
                <ThresholdFilter level="WARN" onMatch="DENY" onMismatch="NEUTRAL"/>
            </Filters>
            <PatternLayout pattern="[%d][%t][%c(类):%L(行)] %m%n"/> 
           <!--  <PatternLayout pattern="[%d][%t] -5level %m%n"/> -->
            <Policies>
                <TimeBasedTriggeringPolicy interval="1" modulate="true"/>
                <SizeBasedTriggeringPolicy size="5 MB"/>
            </Policies>
        </RollingFile>
        <!-- 这里配置了警告日志的格式和存入文件的路径 -->
        <RollingFile name="RollingFileWarn" fileName="${log_path}/warn.log"
                     filePattern="${log_path}/$${date:yyyy-MM}/warn-%d{yyyy-MM-dd}-%i.log">
            <Filters>
              <ThresholdFilter level="WARN"/>
                <ThresholdFilter level="ERROR" onMatch="DENY" onMismatch="NEUTRAL"/>
            </Filters>
             <PatternLayout pattern="[%d][%t][%c(类):%L(行)] %m%n"/> 
            <!-- <PatternLayout pattern="[%d][%t][%p][%c:%L] %m%n"/> -->
            <Policies>
                <TimeBasedTriggeringPolicy interval="1" modulate="true"/>
                <SizeBasedTriggeringPolicy size="5 MB"/>
            </Policies>
        </RollingFile>
        <RollingFile name="RollingFileError" fileName="${log_path}/error.log"
                     filePattern="${log_path}/$${date:yyyy-MM}/error-%d{yyyy-MM-dd}-%i.log">
             <ThresholdFilter level="ERROR"/>
            <PatternLayout pattern="[%d][%t][%c(类):%L(行)] %m%n"/>
           <!--  <PatternLayout pattern="[%d][%t]  %-5level %m%n"/> -->
            <Policies>
                <TimeBasedTriggeringPolicy interval="1" modulate="true"/>
                <SizeBasedTriggeringPolicy size="5 MB"/>
            </Policies>
        </RollingFile>
        <!-- 配置mongdb appender -->
    </appenders>
    <loggers>
    	<!-- 过滤redis重连日志 -->
	   	<logger name="io.lettuce.core.protocol" level="ERROR">
	       	<appender-ref ref="ERROR_FILE" />
	   	</logger>
        <!--过滤掉spring的一些无用的debug信息-->
        <logger name="org.springframework.data.repository.config.RepositoryConfigurationExtensionSupport" level="Error"></logger>
        <logger name="org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerMapping" level="Error"></logger>
        <logger name="org.springframework.boot.actuate.endpoint.web.servlet.WebMvcEndpointHandlerMapping" level="Error"></logger>
        <logger name="org.springframework.amqp.rabbit.connection.CachingConnectionFactory" level="Error"></logger>
        <logger name="org.springframework.amqp.rabbit.listener.SimpleMessageListenerContainer" level="Error"></logger>
        <logger name="org.springframework.boot.web.servlet.FilterRegistrationBean" level="Error"></logger>
        <logger name="org.springframework.jmx.export.annotation.AnnotationMBeanExporter" level="Error"></logger>
        <root level="INFO">
            <appender-ref ref="Console"/><!-- 配置控制台输出日志 -->
            <appender-ref ref="RollingFileInfo"/><!-- 配置普通日志 -->
            <appender-ref ref="RollingFileWarn"/><!-- 配置警告日志 -->
            <appender-ref ref="RollingFileError"/><!-- 配置异常日志 -->
        </root>
    </loggers>
</configuration>

3. This configuration is just fine, you can see the output log information when you start the project, there is a corresponding class, corresponding line number, and corresponding thread name

Insert picture description here
The file path for storing common log, warning log, and abnormal log information (set in the log4j2-spring.xml file)

Insert picture description here

Note: If the log4j2-spring.xml file is not directly placed in the src/main/resources directory, then you need to specify the path in the application.properties file, as shown below, if I put the log4j2-spring.xml file in src/main In the /resources/static directory, the configuration is as follows, and the log output level can also be set

Insert picture description here
Log level: OFF> FATAL> ERROR> WARN> INFO> DEBUG> TRACE> ALL

debug: on behalf of the program debugging log
info: on behalf of general output information
warn: warning information
error: abnormal information
fatal: catastrophic consequences such as system errors

Everyone is welcome to read. I have limited knowledge, and there are inevitably mistakes or omissions in the blog I wrote. I hope you guys can give me some advice. Thank you. I think this article is helpful, just like it

Guess you like

Origin blog.csdn.net/qq_41936224/article/details/108791019