How do you get log4j to roll files based on date and size?

后端 未结 6 595
囚心锁ツ
囚心锁ツ 2020-12-02 17:11

So log4j comes with two existing log rollers: RollingFileAppender, and DailyRollingFileAppender. Has anyone heard of an appender that does both of what the former do?

<
6条回答
  •  隐瞒了意图╮
    2020-12-02 17:48

    Using Log4j

    As @JavaJigs said, Log4j's extras can be used.

    First of all, if you're using Maven, add it as dependency keeping in mind to use the same log4j version, just to avoid any kind of conflict.

    
    
        log4j
        log4j
        1.2.17
    
    
    
    
        log4j
        apache-log4j-extras
        1.2.17
    
    

    Then, set up an appender to use both kinds of rollings. This is a quick and dirty example that rolls every minute and / or when the size of the log files exceeds 1000 bytes.

    
        
            
            
        
        
            
        
        
            
        
    
    

    Add the appender to the logger as you usually do.

    If you run the application you should obtain something like that...

    log4j-current.log
    log4j-18-13.1480266729211.log.gz
    log4j-18-12.1480266729095.log.gz
    log4j-18-12.1480266729123.log.gz
    

    Obviously the numbers of files and their names depend on how your application logs.

    As you can see, the %i placeholder gets replaced with a sort of random yet ever increasing number. I was not able to find a way to have it replaced with number starting from 0 though. Nevertheless, such files listed in alphabetic order should match their historical order.

    Other ideas

    I know you mentioned explicitly log4j. But, if you can, why not to evaluate moving to log4j2? In this log4j2 piece of doc there are a couple of examples that seem to suit your needs.

提交回复
热议问题