编程知识 cdmana.com

Springboot logback log multi file output (split by date and size)

In the early logs Slf4j+Log4j In the way it is used , What we use most is LoggerFactory To get one Logger example ,logback It's the same thing . The example file split in this article is based on log size and date .

Catalog

To configure logback.xml

Configuration needs propery attribute

Configure log append mode

Configure log level

Configure log template

logback Multiple log file operations

logback The official rule of separation by size and time

The log does not delete and control the total file size according to the size  

logback Complete sample configuration

Java Log tool class

System startup log example

Effect of the sample


To configure logback.xml

Configuration needs propery attribute

This part can be configured to logback.properties You need to turn on scanning , The following is directly in logback.xml To configure

 <!-- Set log directory -->
    <property name="LOG_HOME" value="./applog"/>
    <!-- Here we need to value Change to project name -->
    <property name="LOG_NAME" value="patrol-mobile-service"/>

Configure log append mode

To configure appender Tags include file generation rules , Output rules of content, etc

  <!-- Console log format -->
    <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>
    <!--  Log policy file : Generate a log file every day , preservation 30 Days of log files -->
    <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>

Configure log level

Be careful : Log level is case insensitive

  <!-- Default log level , Case is irrelevant :TRACE, DEBUG, INFO, WARN, ERROR, ALL and OFF-->
    <root level="info">
        <appender-ref ref="CONSOLE"/>
        <appender-ref ref="FILE"/>
    </root>

Configure log template

 logger The configuration of is LoggerFactory Template needed , Only if factory acquisition is configured will it take effect .

  <!-- Business operations log -->
    <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 Multiple log file operations

logback The official rule of separation by size and time

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>

The log does not delete and control the total file size according to the size  

Refer to the official instructions :http://logback.qos.ch/manual/appenders.html#TimeBasedRollingPolicy

Need configuration :cleanHistoryOnStart Label value is true The default is false.

<!--  Log policy file : Generate a log file every day , preservation 30 Days of log files -->
    <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 Complete sample configuration

According to a complete configuration example described earlier

<configuration>
    <!-- Set log directory -->
    <property name="LOG_HOME" value="./applog"/>
    <!-- Here we need to value Change to project name -->
    <property name="LOG_NAME" value="patrol-mobile-service"/>
    <!-- Console log format -->
    <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>
    <!--  Log policy file : Generate a log file every day , preservation 30 Days of log files -->
    <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>
    <!--  Log policy file : Generate multiple log files every day -->
    <!-- <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>-->

    <!-- 【 Real time location synchronization 】 Log policy file : Generate a log file every day , preservation 30 Days of log files -->
    <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>
        <!-- Output only INFO journal -->
        <!--<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">
            <!--  receive INFO Level and higher than INFO Level of logging -->
            <level>INFO</level>
        </filter>
        <encoder>
            <pattern>%d{yyyy-MM-dd HH:mm:ss.SSS} [%thread] %-5level %logger{35} | %msg%n</pattern> 
        </encoder>
    </appender>

    <!-- 【 User event synchronization 】 Log policy file : Generate a log file every day , preservation 30 Days of log files -->
    <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>
        <!-- Output only INFO journal -->
        <!--<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">
            <!--  receive INFO Level and higher than INFO Level of logging -->
            <level>INFO</level>
        </filter>
        <encoder>
            <pattern>%d{yyyy-MM-dd HH:mm:ss.SSS} [%thread] %-5level %logger{35} | %msg%n</pattern> 
        </encoder>
    </appender>

    <!-- 【 User trajectory synchronization 】 Piece log strategy : Generate a log file every day , preservation 30 Days of log files -->
    <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>
        <!-- Output only INFO journal -->
        <!--<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">
            <!--  receive INFO Level and higher than INFO Level of logging -->
            <level>INFO</level>
        </filter>
        <encoder>
            <pattern>%d{yyyy-MM-dd HH:mm:ss.SSS} [%thread] %-5level %logger{35} | %msg%n</pattern> 
        </encoder>
    </appender>

    <!-- 【 Event attachment synchronization 】 Log policy file : Generate a log file every day , preservation 30 Days of log files -->
    <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>
        <!-- Output only INFO journal -->
        <!--<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">
            <!--  receive INFO Level and higher than INFO Level of logging -->
            <level>INFO</level>
        </filter>
        <encoder>
            <pattern>%d{yyyy-MM-dd HH:mm:ss.SSS} [%thread] %-5level %logger{35} | %msg%n</pattern> 
        </encoder>
    </appender>

    <!-- 【 System restart service 】 Log policy file : Generate a log file every day , preservation 30 Days of log files -->
    <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>
        <!-- Output only INFO journal -->
        <!--<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">
            <!--  receive INFO Level and higher than INFO Level of logging -->
            <level>INFO</level>
        </filter>
        <encoder>
            <pattern>%d{yyyy-MM-dd HH:mm:ss.SSS} [%thread] %-5level %logger{35} | %msg%n</pattern> 
        </encoder>
    </appender>

    <!-- 【REDIS service 】 Log policy file : Generate a log file every day , preservation 30 Days of log files -->
    <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>
        <!-- Output only INFO journal -->
        <!--<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">
            <!--  receive INFO Level and higher than INFO Level of logging -->
            <level>INFO</level>
        </filter>
        <encoder>
            <pattern>%d{yyyy-MM-dd HH:mm:ss.SSS} [%thread] %-5level %logger{35} | %msg%n</pattern> 
        </encoder>
    </appender>

    <!-- Default log level , Case is irrelevant :TRACE, DEBUG, INFO, WARN, ERROR, ALL and OFF-->
    <root level="info">
        <appender-ref ref="CONSOLE"/>
        <appender-ref ref="FILE"/>
    </root>
    <!-- Specific log level , among xxx Is the project name -->
    <logger name="com.patrol.mobile.controller" level="info" additivity="false">
        <appender-ref ref="CONSOLE"/>
    </logger>

    <!-- Business operations log -->
    <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 Log tool class

Log enumeration can be customized according to the needs of your project .

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:  Log management tools 
 */
public class LoggerUtils {

    /**
     *  Print to the specified file 
     *
     * @param patrolLoggerType  Log file type 
     * @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:  Patrol log type enumeration 
     */
    public enum PatrolLoggerType {
        /**
         *  Restart the log 
         */
        RESTART("RESTART_LOG"),
        /**
         *  Real time location 
         */
        POSITION("POSITION_LOG"),
        /**
         *  User events 
         */
        EVENT("EVENT_LOG"),
        /**
         *  User trajectory 
         */
        TRACK("TRACK_LOG"),
        /**
         *  Event attachment 
         */
        FILE("FILE_LOG");

        private String logFileName;

        PatrolLoggerType(String fileName) {
            this.logFileName = fileName;
        }

        public String getLogFileName() {
            return logFileName;
        }


    }
}

System startup log example

stay Application Start class call log output .

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;

/**
 *  Start asynchronous request 
 */
@EnableAsync
/**
 *  Turn on the interface cache 
 */
@EnableCaching
/**
 *  Enable scheduled task scheduling 
 */
@EnableScheduling
/**
 *  Open interface document description 
 */
@EnableSwagger2
/**
 * @SpringBootApplication
 * <p> amount to @Configuration,@EnableAutoConfiguration and  @ComponentScan </p>
 */
@SpringBootApplication
public class PatrolMobileServiceApplication {
    /**
     *  System restart log output ( Specify log file output )
     */
    @PostConstruct
    public void printLog() {
        Logger logger = LoggerUtils.getLogger(LoggerUtils.PatrolLoggerType.RESTART);
        logger.info(">>> System restart !");
    }

    public static void main(String[] args) {
        SpringApplication.run(PatrolMobileServiceApplication.class, args);
    }

}

Effect of the sample

 

 

版权声明
本文为[boonya]所创,转载请带上原文链接,感谢

Scroll to Top