springboot-整合log4j2

springboot-整合log4j2

起男 246 2023-10-25

springboot-整合log4j2

导入依赖

springboot默认使用的是logback

        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-web</artifactId>
          <!-- 去掉springboot默认配置 -->
            <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>

创建配置文件

在resources目录下创建log4j2.xml文件

<?xml version="1.0" encoding="UTF-8"?>
<configuration>

    <properties>
        <!--日志输出位置-->
        <property name="LOG_HOME">logs</property>
    </properties>
    <Appenders>
        <!-- 将日志输出到控制台-->
        <Console name="CONSOLE" target="SYSTEM_OUT">
            <!--设置日志格式及颜色-->
            <PatternLayout
                    pattern="[%style{%d}{bright,green}][%highlight{%p}][%style{%t}{bright,blue}][%style{%C}{bright,yellow}]: %msg%n%style{%throwable}{red}"
                    disableAnsi="false" noConsoleNoAnsi="false"/>
        </Console>
        <!-- 将日志输出到文件-->
        <RollingFile name="FILE-APPENDER"
                     fileName="${LOG_HOME}/log4j2-demo.log"
                     filePattern="${LOG_HOME}/log4j2-demo-%d{yyyy-MM-dd}-%i.log">
            <!--设置日志格式-->
            <PatternLayout>
                <pattern>[%d][%p][%t][%C]%m%n</pattern>
            </PatternLayout>
            <Policies>
                <!-- 设置日志文件切分参数 -->
                <SizeBasedTriggeringPolicy size="100 MB"/>
                <TimeBasedTriggeringPolicy/>
            </Policies>
            <!--设置最大存档数-->
            <DefaultRolloverStrategy max="20"/>
        </RollingFile>
    </Appenders>
    <Loggers>
        <!-- 根日志设置 -->
        <Root level="debug">
            <AppenderRef ref="CONSOLE" level="debug"/>
            <AppenderRef ref="FILE-APPENDER" level="info"/>
        </Root>
        <!--spring日志-->
        <Logger name="org.springframework" level="info"/>
        <!-- mybatis日志 -->
        <Logger name="com.mybatis" level="warn"/>
    </Loggers>
</configuration>

注意:
如果文件的名称不叫log4j2.xml或者文件路径不在resources目录下,则需要在application里通过logging.config配置