How to add the date timestamp to log4j2 logfiles?

前端 未结 5 1914
无人及你
无人及你 2021-02-14 04:03

I want to create day dependent logfiles with log4j2:


<
5条回答
  •  北海茫月
    2021-02-14 04:43

    Use ASizeBasedTriggeringPolicy class in appender. You can even append the current second to the logfile name. %d{yyyy_MM_dd HH.mm.ss}

    import org.apache.logging.log4j.core.LogEvent;
    import org.apache.logging.log4j.core.appender.rolling.*;
    import org.apache.logging.log4j.core.config.plugins.Plugin;
    import org.apache.logging.log4j.core.config.plugins.PluginAttribute;
    import org.apache.logging.log4j.core.config.plugins.PluginFactory;
    
    @Plugin(name = "ASizeBasedTriggeringPolicy",
            category = "Core",
            printObject = true
    )
    public class ASizeBasedTriggeringPolicy extends AbstractTriggeringPolicy {
        private SizeBasedTriggeringPolicy sizeBasedTriggeringPolicy;
        private RollingFileManager aManager;
    
        protected ASizeBasedTriggeringPolicy(String maxFileSize) {
            sizeBasedTriggeringPolicy = SizeBasedTriggeringPolicy.createPolicy(maxFileSize);
    
        }
    
        public void initialize(RollingFileManager aManager) {
            sizeBasedTriggeringPolicy.initialize(aManager);
            this.aManager = aManager;
        }
    
        public boolean isTriggeringEvent(LogEvent event) {
            if (sizeBasedTriggeringPolicy.isTriggeringEvent(event)) {
                aManager.getPatternProcessor().setPrevFileTime(System.currentTimeMillis());
                return true;
            } else {
                return false;
            }
        }
    
        @PluginFactory
        public static ASizeBasedTriggeringPolicy createPolicy(@PluginAttribute("size") String size) {
            return new ASizeBasedTriggeringPolicy(size);
        }
    }
    

    Then use ASizeBasedTriggeringPolicy in log appender

    
        ...
        ... 
        
             
        
    
    

提交回复
热议问题