logback.xml日志文件配置

时间:2022-09-10 21:55:18
logback.xml日志文件配置

                  在项目当中日志也成为必不可少的一部分,除了再控制台上打印控制台日志以外,在服务器上运行时候日志都是记录到日志文件里面,那么日志文件一般是怎么配置的,放在哪个目录下面呢,这些都是需要我们思考的,首先我们看下日志引进都需要哪些包:

<!--与日志相关的jar -->
<dependency>
<groupId>org.slf4j</groupId>
<artifactId>slf4j-api</artifactId>
<version>1.7.2</version>
</dependency>
<dependency>
<groupId>ch.qos.logback</groupId>
<artifactId>logback-core</artifactId>
<version>1.0.13</version>
</dependency>
<dependency>
<groupId>ch.qos.logback</groupId>
<artifactId>logback-classic</artifactId>
<version>1.0.13</version>
</dependency>

下面就是配置文件写法,命名为logback.xml放到src/main/resources根目录下,程序会自动加载日志文件

<?xml version="1.0" encoding="UTF-8"?>
<configuration>
<contextName>logback-4001</contextName>
<jmxConfigurator />
<!-- 日志路径 -->
<property name="LOG_HOME" value=" /home/spirits/service/logs/" />

<!-- console控制台日志 -->
<appender name="stdout" class="ch.qos.logback.core.ConsoleAppender">
<layout class="ch.qos.logback.classic.PatternLayout">
<pattern>%d{yyyy-MM-dd HH:mm:ss.SSS} [%thread] %-5level %logger{50} - %msg%n</pattern>
</layout>
</appender>

<!-- 程序运行日志记录-3天-->
<appender name="INFO_FILE" class="ch.qos.logback.core.rolling.RollingFileAppender">
<rollingPolicy class="ch.qos.logback.core.rolling.TimeBasedRollingPolicy">
<FileNamePattern>${LOG_HOME}/info/spirit-info-%d{yyyy-MM-dd}.log</FileNamePattern>
<MaxHistory>3</MaxHistory> <!--保存天数 -->
</rollingPolicy>
<layout class="ch.qos.logback.classic.PatternLayout">
<pattern>%d{yyyy-MM-dd HH:mm:ss.SSS} [%thread] %-5level %logger{50} - %msg%n </pattern>
</layout>
</appender>

<!-- 错误日志记录-15天 -->
<appender name="ERROR_FILE" class="ch.qos.logback.core.rolling.RollingFileAppender">
<rollingPolicy class="ch.qos.logback.core.rolling.TimeBasedRollingPolicy">
<FileNamePattern>${LOG_HOME}/error/spirit-error-%d{yyyy-MM-dd}.log</FileNamePattern>
<MaxHistory>15</MaxHistory>
</rollingPolicy>
<filter class="ch.qos.logback.classic.filter.LevelFilter">
<level>ERROR</level>
<onMatch>ACCEPT</onMatch>
<onMismatch>DENY</onMismatch>
</filter>
<layout class="ch.qos.logback.classic.PatternLayout">
<pattern>%d{yyyy-MM-dd HH:mm:ss.SSS} [%thread] %-5level %logger{50} - %msg%n </pattern>
</layout>
</appender>

<root level="info">
<appender-ref ref="stdout" />
<appender-ref ref="ERROR_FILE" />
<appender-ref ref="INFO_FILE" />
</root>

</configuration>

若不放到src/main/resources根目录下,则需要引入,比如此时放在src/main/resources/META-INF/logback/下,文件名为logback-test.xml,则需要在src/main/resources根目录下面新建logback.xml,配置如下:

<?xml version="1.0" encoding="UTF-8"?>
<configuration>
<include resource="META-INF/logback/logback-test.xml"/>
</configuration>