How to roll the log file on startup in logback

前端 未结 11 1711
梦谈多话
梦谈多话 2020-12-02 12:50

I would like to configure logback to do the following.

  • Log to a file
  • Roll the file when it reaches 50MB
  • Only keep 7 days worth of logs
  • <
11条回答
  •  旧巷少年郎
    2020-12-02 13:51

    I found another solution for rolling the logFile once, when the application starts.

    I use logback's RollingFileAppender with logback's FixedWindowRollingPolicy and my own implementation of a TriggeringPolicy.

    The FixedWindowRollingPolicy gets the fileNamePattern for the new logFile, where %1 is the new number of the file. The maxIndex stands for the maximum number of my "history". More information: FixedWindowRollingPolicy

    My implementations TriggeringPolicy returns true for the first time, when isTriggeringEvent(...) gets called. So the WindowRollingPolicy rolls over the logfiles, when the Policy gets called the first time, and afterwards it will not roll over again.

    The xml-configuration for the RollingFileAppender:

    
        ...
        
            logFile.log
    
            
                logFile.%i.log
                1
                4
            
    
            
        
    ...
    
    

    The TriggeringPolicy:

    package my.classpath;
    
    import ch.qos.logback.core.rolling.TriggeringPolicyBase;
    
    import java.io.File;
    
    public class RollOncePerSessionTriggeringPolicy extends TriggeringPolicyBase {
        private static boolean doRolling = true;
    
        @Override
        public boolean isTriggeringEvent(File activeFile, E event) {
            // roll the first time when the event gets called
            if (doRolling) {
                doRolling = false;
                return true;
            }
            return false;
        }
    }
    

提交回复
热议问题