java

关注公众号 jb51net

关闭
首页 > 软件编程 > java > Springboot Logback日志多文件输出

Springboot Logback日志多文件输出方式(按日期和大小分割)

作者:boonya

这篇文章主要介绍了Springboot Logback日志多文件输出方式(按日期和大小分割),具有很好的参考价值,希望对大家有所帮助,如有错误或未考虑完全的地方,望不吝赐教

在早期的日志Slf4j+Log4j使用方式中,我们使用最多的就是LoggerFactory来获取一个Logger实例,logback的原理也一样。

本文示例文件分割按照日志大小和日期进行分割。

配置logback.xml

配置需要的propery属性

这部分可以配置到logback.properties 需要开启扫描才行,下面是直接在logback.xml配置

 <!--设置日志目录-->
    <property name="LOG_HOME" value="./applog"/>
    <!--这里需要将value改成项目名称-->
    <property name="LOG_NAME" value="patrol-mobile-service"/>

配置日志追加方式

配置appender标签包括文件生成规则,内容的输出规则等

  <!--控制台日志格式-->
    <appender name="CONSOLE" class="ch.qos.logback.core.ConsoleAppender">
        <encoder>
            <pattern>%d{yyyy-MM-dd HH:mm:ss.SSS} [%thread] %-5level %logger{35} | %msg%n</pattern>
        </encoder>
    </appender>
    <!-- 文件日志策略:每天生成一个日志文件,保存30天的日志文件-->
    <appender name="FILE" class="ch.qos.logback.core.rolling.RollingFileAppender">
        <rollingPolicy class="ch.qos.logback.core.rolling.SizeAndTimeBasedRollingPolicy">
            <fileNamePattern>${LOG_HOME}/${LOG_NAME}.%d{yyyy-MM-dd}.%i.log</fileNamePattern>
            <maxFileSize>100MB</maxFileSize>
            <maxHistory>30</maxHistory>
            <totalSizeCap>10GB</totalSizeCap>
            <cleanHistoryOnStart>true</cleanHistoryOnStart>
        </rollingPolicy>
         
        <encoder>
            <pattern>%d{yyyy-MM-dd HH:mm:ss.SSS} [%thread] %-5level %logger{35} | %msg%n</pattern> 
        </encoder>
    </appender>

配置日志级别

注意:日志级别不区分大小写

  <!--默认日志级别,大小写无关:TRACE, DEBUG, INFO, WARN, ERROR, ALL和OFF-->
    <root level="info">
        <appender-ref ref="CONSOLE"/>
        <appender-ref ref="FILE"/>
    </root>

配置日志模板

logger的配置就是LoggerFactory需要的模板,只有配置了工厂获取才会生效。

  <!--业务操作日志-->
    <logger name="POSITION_LOG" level="info" additivity="false">
        <appender-ref ref="POSITION_LOG_APPENDER"/>
    </logger>
    <logger name="EVENT_LOG" level="info" additivity="false">
        <appender-ref ref="EVENT_LOG_APPENDER"/>
    </logger>
    <logger name="TRACK_LOG" level="info" additivity="false">
        <appender-ref ref="TRACK_LOG_APPENDER"/>
    </logger>
    <logger name="FILE_LOG" level="info" additivity="false">
        <appender-ref ref="FILE_LOG_APPENDER"/>
    </logger>
    <logger name="RESTART_LOG" level="info" additivity="false">
        <appender-ref ref="RESTART_LOG_APPENDER"/>
    </logger>

logback 多日志文件操作

logback 官方按大小和时间分隔规则

http://logback.qos.ch/manual/appenders.html

<configuration>
  <appender name="ROLLING" class="ch.qos.logback.core.rolling.RollingFileAppender">
    <file>mylog.txt</file>
    <rollingPolicy class="ch.qos.logback.core.rolling.SizeAndTimeBasedRollingPolicy">
      <!-- rollover daily -->
      <fileNamePattern>mylog-%d{yyyy-MM-dd}.%i.txt</fileNamePattern>
       <!-- each file should be at most 100MB, keep 60 days worth of history, but at most 20GB -->
       <maxFileSize>100MB</maxFileSize>    
       <maxHistory>60</maxHistory>
       <totalSizeCap>20GB</totalSizeCap>
    </rollingPolicy>
    <encoder>
      <pattern>%msg%n</pattern>
    </encoder>
  </appender>
 
 
  <root level="DEBUG">
    <appender-ref ref="ROLLING" />
  </root>
 
</configuration>

日志未按照大小删除和控制文件总大小

参考官方说明:http://logback.qos.ch/manual/appenders.html#TimeBasedRollingPolicy

需要配置:cleanHistoryOnStart标签值为true默认是false.

<!-- 文件日志策略:每天生成一个日志文件,保存30天的日志文件-->
    <appender name="FILE" class="ch.qos.logback.core.rolling.RollingFileAppender">
        <rollingPolicy class="ch.qos.logback.core.rolling.SizeAndTimeBasedRollingPolicy">
            <fileNamePattern>${LOG_HOME}/${LOG_NAME}.%d{yyyy-MM-dd}.%i.log</fileNamePattern>
            <maxFileSize>100MB</maxFileSize>
            <maxHistory>30</maxHistory>
            <totalSizeCap>10GB</totalSizeCap>
            <cleanHistoryOnStart>true</cleanHistoryOnStart>
        </rollingPolicy>
        <encoder>
            <pattern>%d{yyyy-MM-dd HH:mm:ss.SSS} [%thread] %-5level %logger{35} | %msg%n</pattern> 
        </encoder>
    </appender>

logback完整示例配置

根据前面介绍的一个完整配置示例

<configuration>
    <!--设置日志目录-->
    <property name="LOG_HOME" value="./applog"/>
    <!--这里需要将value改成项目名称-->
    <property name="LOG_NAME" value="patrol-mobile-service"/>
    <!--控制台日志格式-->
    <appender name="CONSOLE" class="ch.qos.logback.core.ConsoleAppender">
        <encoder>
            <pattern>%d{yyyy-MM-dd HH:mm:ss.SSS} [%thread] %-5level %logger{35} | %msg%n</pattern>
        </encoder>
    </appender>
    <!-- 文件日志策略:每天生成一个日志文件,保存30天的日志文件-->
    <appender name="FILE" class="ch.qos.logback.core.rolling.RollingFileAppender">
        <rollingPolicy class="ch.qos.logback.core.rolling.SizeAndTimeBasedRollingPolicy">
            <fileNamePattern>${LOG_HOME}/${LOG_NAME}.%d{yyyy-MM-dd}.%i.log</fileNamePattern>
            <maxFileSize>100MB</maxFileSize>
            <maxHistory>30</maxHistory>
            <totalSizeCap>10GB</totalSizeCap>
            <cleanHistoryOnStart>true</cleanHistoryOnStart>
        </rollingPolicy>
        <encoder>
            <pattern>%d{yyyy-MM-dd HH:mm:ss.SSS} [%thread] %-5level %logger{35} | %msg%n</pattern> 
        </encoder>
    </appender>
    <!-- 文件日志策略:每天生成多个日志文件-->
    <!-- <appender name="FILE" class="ch.qos.logback.core.rolling.RollingFileAppender">
         <file>${LOG_HOME}/${LOG_NAME}.log</file>
         <rollingPolicy class="ch.qos.logback.core.rolling.FixedWindowRollingPolicy">      
             <fileNamePattern>${LOG_HOME}/${LOG_NAME}.%d{yyyy-MM-dd}.%i.zip</fileNamePattern>  
             <minIndex>1</minIndex>
             <maxIndex>1000</maxIndex>
         </rollingPolicy>
         <triggeringPolicy class="ch.qos.logback.core.rolling.SizeBasedTriggeringPolicy">       
             <maxFileSize>100MB</maxFileSize>  
         </triggeringPolicy>  
         <encoder>    
             <pattern> %d{yyyy-MM-dd HH:mm:ss.SSS} [%thread] %-5level %logger{35} - %msg%n</pattern>  
         </encoder>
     </appender>-->
 
    <!-- 【实时位置同步】文件日志策略:每天生成一个日志文件,保存30天的日志文件-->
    <appender name="POSITION_LOG_APPENDER" class="ch.qos.logback.core.rolling.RollingFileAppender">
        <rollingPolicy class="ch.qos.logback.core.rolling.SizeAndTimeBasedRollingPolicy">
            <fileNamePattern>${LOG_HOME}/${LOG_NAME}-position-sync.%d{yyyy-MM-dd}.%i.log</fileNamePattern>
            <maxFileSize>100MB</maxFileSize>
            <maxHistory>30</maxHistory>
            <totalSizeCap>10GB</totalSizeCap>
            <cleanHistoryOnStart>true</cleanHistoryOnStart>
        </rollingPolicy>
        <!--仅输出INFO日志-->
        <!--<filter class="ch.qos.logback.classic.filter.LevelFilter">
            <level>INFO</level>
            <onMatch>ACCEPT</onMatch>
            <onMismatch>DENY</onMismatch>
        </filter>-->
        <filter class="ch.qos.logback.classic.filter.ThresholdFilter">
            <!-- 接收INFO级别和高于INFO级别的日志-->
            <level>INFO</level>
        </filter>
        <encoder>
            <pattern>%d{yyyy-MM-dd HH:mm:ss.SSS} [%thread] %-5level %logger{35} | %msg%n</pattern> 
        </encoder>
    </appender>
 
    <!-- 【用户事件同步】文件日志策略:每天生成一个日志文件,保存30天的日志文件-->
    <appender name="EVENT_LOG_APPENDER" class="ch.qos.logback.core.rolling.RollingFileAppender">
        <rollingPolicy class="ch.qos.logback.core.rolling.SizeAndTimeBasedRollingPolicy">
            <fileNamePattern>${LOG_HOME}/${LOG_NAME}-event-sync.%d{yyyy-MM-dd}.%i.log</fileNamePattern>
            <maxFileSize>100MB</maxFileSize>
            <maxHistory>30</maxHistory>
            <totalSizeCap>10GB</totalSizeCap>
            <cleanHistoryOnStart>true</cleanHistoryOnStart>
        </rollingPolicy>
        <!--仅输出INFO日志-->
        <!--<filter class="ch.qos.logback.classic.filter.LevelFilter">
            <level>INFO</level>
            <onMatch>ACCEPT</onMatch>
            <onMismatch>DENY</onMismatch>
        </filter>-->
        <filter class="ch.qos.logback.classic.filter.ThresholdFilter">
            <!-- 接收INFO级别和高于INFO级别的日志-->
            <level>INFO</level>
        </filter>
        <encoder>
            <pattern>%d{yyyy-MM-dd HH:mm:ss.SSS} [%thread] %-5level %logger{35} | %msg%n</pattern> 
        </encoder>
    </appender>
 
    <!-- 【用户轨迹同步】件日志策略:每天生成一个日志文件,保存30天的日志文件-->
    <appender name="TRACK_LOG_APPENDER" class="ch.qos.logback.core.rolling.RollingFileAppender">
        <rollingPolicy class="ch.qos.logback.core.rolling.SizeAndTimeBasedRollingPolicy">
            <fileNamePattern>${LOG_HOME}/${LOG_NAME}-track-sync.%d{yyyy-MM-dd}.%i.log</fileNamePattern>
            <maxFileSize>100MB</maxFileSize>
            <maxHistory>30</maxHistory>
            <totalSizeCap>10GB</totalSizeCap>
            <cleanHistoryOnStart>true</cleanHistoryOnStart>
        </rollingPolicy>
        <!--仅输出INFO日志-->
        <!--<filter class="ch.qos.logback.classic.filter.LevelFilter">
            <level>INFO</level>
            <onMatch>ACCEPT</onMatch>
            <onMismatch>DENY</onMismatch>
        </filter>-->
        <filter class="ch.qos.logback.classic.filter.ThresholdFilter">
            <!-- 接收INFO级别和高于INFO级别的日志-->
            <level>INFO</level>
        </filter>
        <encoder>
            <pattern>%d{yyyy-MM-dd HH:mm:ss.SSS} [%thread] %-5level %logger{35} | %msg%n</pattern> 
        </encoder>
    </appender>
 
    <!-- 【事件附件同步】文件日志策略:每天生成一个日志文件,保存30天的日志文件-->
    <appender name="FILE_LOG_APPENDER" class="ch.qos.logback.core.rolling.RollingFileAppender">
        <rollingPolicy class="ch.qos.logback.core.rolling.SizeAndTimeBasedRollingPolicy">
            <fileNamePattern>${LOG_HOME}/${LOG_NAME}-file-sync.%d{yyyy-MM-dd}.%i.log</fileNamePattern>
            <maxFileSize>100MB</maxFileSize>
            <maxHistory>30</maxHistory>
            <totalSizeCap>10GB</totalSizeCap>
            <cleanHistoryOnStart>true</cleanHistoryOnStart>
        </rollingPolicy>
        <!--仅输出INFO日志-->
        <!--<filter class="ch.qos.logback.classic.filter.LevelFilter">
            <level>INFO</level>
            <onMatch>ACCEPT</onMatch>
            <onMismatch>DENY</onMismatch>
        </filter>-->
        <filter class="ch.qos.logback.classic.filter.ThresholdFilter">
            <!-- 接收INFO级别和高于INFO级别的日志-->
            <level>INFO</level>
        </filter>
        <encoder>
            <pattern>%d{yyyy-MM-dd HH:mm:ss.SSS} [%thread] %-5level %logger{35} | %msg%n</pattern> 
        </encoder>
    </appender>
 
    <!-- 【系统重启服务】文件日志策略:每天生成一个日志文件,保存30天的日志文件-->
    <appender name="RESTART_LOG_APPENDER" class="ch.qos.logback.core.rolling.RollingFileAppender">
        <rollingPolicy class="ch.qos.logback.core.rolling.SizeAndTimeBasedRollingPolicy">
            <fileNamePattern>${LOG_HOME}/${LOG_NAME}-restart.%d{yyyy-MM-dd}.%i.log</fileNamePattern>
            <maxFileSize>100MB</maxFileSize>
            <maxHistory>30</maxHistory>
            <totalSizeCap>10GB</totalSizeCap>
            <cleanHistoryOnStart>true</cleanHistoryOnStart>
        </rollingPolicy>
        <!--仅输出INFO日志-->
        <!--<filter class="ch.qos.logback.classic.filter.LevelFilter">
            <level>INFO</level>
            <onMatch>ACCEPT</onMatch>
            <onMismatch>DENY</onMismatch>
        </filter>-->
        <filter class="ch.qos.logback.classic.filter.ThresholdFilter">
            <!-- 接收INFO级别和高于INFO级别的日志-->
            <level>INFO</level>
        </filter>
        <encoder>
            <pattern>%d{yyyy-MM-dd HH:mm:ss.SSS} [%thread] %-5level %logger{35} | %msg%n</pattern> 
        </encoder>
    </appender>
 
    <!-- 【REDIS服务】文件日志策略:每天生成一个日志文件,保存30天的日志文件-->
    <appender name="REDIS_LOG_APPENDER" class="ch.qos.logback.core.rolling.RollingFileAppender">
        <rollingPolicy class="ch.qos.logback.core.rolling.SizeAndTimeBasedRollingPolicy">
            <fileNamePattern>${LOG_HOME}/${LOG_NAME}-redis.%d{yyyy-MM-dd}.%i.log</fileNamePattern>
            <maxFileSize>100MB</maxFileSize>
            <maxHistory>30</maxHistory>
            <totalSizeCap>10GB</totalSizeCap>
            <cleanHistoryOnStart>true</cleanHistoryOnStart>
        </rollingPolicy>
        <!--仅输出INFO日志-->
        <!--<filter class="ch.qos.logback.classic.filter.LevelFilter">
            <level>INFO</level>
            <onMatch>ACCEPT</onMatch>
            <onMismatch>DENY</onMismatch>
        </filter>-->
        <filter class="ch.qos.logback.classic.filter.ThresholdFilter">
            <!-- 接收INFO级别和高于INFO级别的日志-->
            <level>INFO</level>
        </filter>
        <encoder>
            <pattern>%d{yyyy-MM-dd HH:mm:ss.SSS} [%thread] %-5level %logger{35} | %msg%n</pattern> 
        </encoder>
    </appender>
 
    <!--默认日志级别,大小写无关:TRACE, DEBUG, INFO, WARN, ERROR, ALL和OFF-->
    <root level="info">
        <appender-ref ref="CONSOLE"/>
        <appender-ref ref="FILE"/>
    </root>
    <!--特定日志级别,其中xxx为项目名称-->
    <logger name="com.patrol.mobile.controller" level="info" additivity="false">
        <appender-ref ref="CONSOLE"/>
    </logger>
 
    <!--业务操作日志-->
    <logger name="POSITION_LOG" level="info" additivity="false">
        <appender-ref ref="POSITION_LOG_APPENDER"/>
    </logger>
    <logger name="EVENT_LOG" level="info" additivity="false">
        <appender-ref ref="EVENT_LOG_APPENDER"/>
    </logger>
    <logger name="TRACK_LOG" level="info" additivity="false">
        <appender-ref ref="TRACK_LOG_APPENDER"/>
    </logger>
    <logger name="FILE_LOG" level="info" additivity="false">
        <appender-ref ref="FILE_LOG_APPENDER"/>
    </logger>
    <logger name="RESTART_LOG" level="info" additivity="false">
        <appender-ref ref="RESTART_LOG_APPENDER"/>
    </logger>
    <logger name="REDIS_LOG" level="info" additivity="false">
        <appender-ref ref="REDIS_LOG_APPENDER"/>
    </logger>
</configuration>

Java日志工具类

日志枚举根据自己项目的需要进行自定义即可。

package com.patrol.beans.util;
 
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
 
/**
 * @Copyright: 2019-2021
 * @FileName: LoggerUtils.java
 * @Author: PJL
 * @Date: 2020/9/8 10:34
 * @Description: 日志管理工具
 */
public class LoggerUtils {
 
    /**
     * 打印到指定的文件下
     *
     * @param patrolLoggerType 日志文件类型
     * @return
     */
    public static Logger getLogger(PatrolLoggerType patrolLoggerType) {
        return LoggerFactory.getLogger(patrolLoggerType.getLogFileName());
    }
 
    /**
     * @Copyright: 2019-2021
     * @FileName: PatrolLoggerType.java
     * @Author: PJL
     * @Date: 2020/9/8 10:10
     * @Description: 巡护日志类型枚举
     */
    public enum PatrolLoggerType {
        /**
         * 重启日志
         */
        RESTART("RESTART_LOG"),
        /**
         * 实时位置
         */
        POSITION("POSITION_LOG"),
        /**
         * 用户事件
         */
        EVENT("EVENT_LOG"),
        /**
         * 用户轨迹
         */
        TRACK("TRACK_LOG"),
        /**
         * 事件附件
         */
        FILE("FILE_LOG");
 
        private String logFileName;
 
        PatrolLoggerType(String fileName) {
            this.logFileName = fileName;
        }
 
        public String getLogFileName() {
            return logFileName;
        }
 
 
    }
}

系统启动日志示例

在Application启动类调用日志输出。

package com.patrol.mobile;
 
import com.patrol.beans.util.LoggerUtils;
import org.slf4j.Logger;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.cache.annotation.EnableCaching;
import org.springframework.scheduling.annotation.EnableAsync;
import org.springframework.scheduling.annotation.EnableScheduling;
import springfox.documentation.swagger2.annotations.EnableSwagger2;
 
import javax.annotation.PostConstruct;
 
/**
 * 开启异步请求
 */
@EnableAsync
/**
 * 开启接口缓存
 */
@EnableCaching
/**
 * 开启定时任务调度
 */
@EnableScheduling
/**
 * 开启接口文档描述
 */
@EnableSwagger2
/**
 * @SpringBootApplication
 * <p>相当于@Configuration,@EnableAutoConfiguration和 @ComponentScan </p>
 */
@SpringBootApplication
public class PatrolMobileServiceApplication {
    /**
     * 系统重启日志输出(指定日志文件输出)
     */
    @PostConstruct
    public void printLog() {
        Logger logger = LoggerUtils.getLogger(LoggerUtils.PatrolLoggerType.RESTART);
        logger.info(">>>系统重启!");
    }
 
    public static void main(String[] args) {
        SpringApplication.run(PatrolMobileServiceApplication.class, args);
    }
 
}

示例效果

总结

以上为个人经验,希望能给大家一个参考,也希望大家多多支持脚本之家。

您可能感兴趣的文章:
阅读全文