How to roll the log file on startup in logback

前端 未结 11 1755
梦谈多话
梦谈多话 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:48

    Ceki's solution doesn't appear to work for me, but seems to be part way there at least.

    It blows up because it can't see the rolling policy when starting the TimeBasedFileNamingAndTriggeringPolicyBase. With some hackery I got it to do some logging, and with some more I got it to observe the trigger, but then it broke again because it couldn't resolve one of the filename properties... The package is a logback one so I could get to some of the internals, to replicate some of the logic in SizeAndTimeBasedFNATP#isTriggeringEvent and call computeCurrentPeriodsHighestCounterValue. I think something along those lines might work, just haven't found the magic combination yet. I really hope I'm doing something silly, because otherwise I think it will mean either opening up some of the details for subclassing, or putting this straight into logback as another rolling/triggering policy.

    logback.xml: tried various orderings of triggeringPolicy, TimeBasedFileNamingAndTriggeringPolicy inside and outside the rollingPolicy.

    
        ${LOG_DIR}/${LOG_FILE_BASE}.log
        
            ${LOG_DIR}/${LOG_FILE_BASE}.%d{yyyy-MM-dd}.%i.log
            7
    
            
        
    
        
            INFO
        
    
        
            %msg%n
        
    
    

    The trigger policy:

    package ch.qos.logback.core.rolling;
    public class RollOnStartupPolicy extends SizeAndTimeBasedFNATP {
    private final AtomicBoolean firstTime = new AtomicBoolean(true);
    
        @Override
        public boolean isTriggeringEvent(File activeFile, E event) {
            if (!firstTime.get()) { // fast path
                return false;
            }
    
            if (firstTime.getAndSet(false)) {
                return true;
            }
            return false;
        }
    }
    

    The exception:

    java.lang.NullPointerException
    at  at ch.qos.logback.core.rolling.TimeBasedFileNamingAndTriggeringPolicyBase.start(TimeBasedFileNamingAndTriggeringPolicyBase.java:46)
    at  at ch.qos.logback.core.rolling.SizeAndTimeBasedFNATP.start(SizeAndTimeBasedFNATP.java:36)
    at  at ch.qos.logback.core.joran... [snip joran config]
    

提交回复
热议问题