springMvc之配置logback

凤伟泽
2023-12-01

1、添加依赖

<dependency>
    <groupId>org.logback-extensions</groupId>
    <!--logback监听器在该依赖中。该依赖中包含slf4j-api、logback-classic、logback-core三个依赖
-->
    <artifactId>logback-ext-spring</artifactId>
    <version>0.1.4</version>
</dependency>

2、配置logback配置文件

<?xml version="1.0" encoding="UTF-8"?>
<configuration>
    <!-- Where are log files -->
    <property name="LOG_HOME" value="./" />
    <!-- Console log output -->
    <appender name="Console" class="ch.qos.logback.core.ConsoleAppender">
        <encoder>
            <!-- 格式化输出:%d:表示日期 %thread:表示线程名 %-5level:级别从左显示5个字符宽度-->
            <pattern>%d{HH:mm:ss.SSS} [%thread] > %green(%-5level) %cyan(%logger{35}) - %m%n</pattern>
        </encoder>
    </appender>

    <!-- Log file debug output -->
    <appender name="File" class="ch.qos.logback.core.rolling.RollingFileAppender">
        <rollingPolicy class="ch.qos.logback.core.rolling.TimeBasedRollingPolicy">
            <fileNamePattern>F:/logs/%d{yyyy-MM-dd}.log.zip</fileNamePattern>
            <!--日志最大保存时间-->
            <maxHistory>365</maxHistory>
        </rollingPolicy>
        <encoder>
            <pattern>%d{yyyy-MM-dd HH:mm:ss.SSS} > %-5level %X{X-B3-TraceId:-} ${springAppName:-} %logger{35} %m%n</pattern>
        </encoder>
    </appender>
    <!--debug:级别最高级别 开发
        info: 信息
        error:错误级别 项目上线
    -->
    <root level="debug">
        <appender-ref ref="Console"/>
        <appender-ref ref="File"/>
    </root>
</configuration>

3、配置web.xml

 <!-- logback 加载那个日志文件-->
    <context-param>
        <param-name>logbackConfigLocation</param-name>
        <!--logback.xml放在resources/config路径下-->
        <param-value>classpath:logback.xml</param-value>
    </context-param>
    <listener>
        <listener-class>ch.qos.logback.ext.spring.web.LogbackConfigListener</listener-class>
    </listener>

 类似资料: