Logback - 如何通过配置文件设置具有新开始和新日期的滚动日志

时间:2012-05-17 08:25:09

标签: java logging

嗨,有什么方法可以在应用程序启动时设置滚动日志,或者是新的一天,并通过配置文件保存30天或1个月(不是30个文件)的历史记录。我找了好几个小时,但没什么。可能这种方式不存在,需要写。

<configuration>
    <appender name="STDOUT" class="ch.qos.logback.core.ConsoleAppender">
        <encoder>
            <pattern>%d [%thread] %-5level %logger{50} - %msg%n
            </pattern>
        </encoder>
    </appender>

    <appender name="FILE" class="ch.qos.logback.core.rolling.RollingFileAppender">
        <file>/logs/server.log</file>
        <encoder>
            <pattern>%d [%thread] %-5level %logger{50} - %msg%n
            </pattern>
        </encoder>

        <!-- Join this time based rolling with-->
        <rollingPolicy class="ch.qos.logback.core.rolling.TimeBasedRollingPolicy">
            <fileNamePattern>/logs/server.%d{yyyy-MM-dd}.log.zip</fileNamePattern>
            <!-- Mean 30 days not 30 files -->
            <maxHistory>30</maxHistory> 
        </rollingPolicy>

        <!-- New start baser Rolling-->
        ...
    </appender>

    <root level="INFO">
    <appender-ref ref="STDOUT" />
        <appender-ref ref="FILE" />
    </root>

</configuration>

1 个答案:

答案 0 :(得分:0)

此问题重复并由https://stackoverflow.com/a/30801658/844648

回答

我终于明白了。我可以按大小,时间和启动来滚动。这是解决方案:

1创建自己的班级

@NoAutoStart
public class StartupSizeTimeBasedTriggeringPolicy<E> extends SizeAndTimeBasedFNATP<E> {

    private boolean started = false;

    @Override
    public boolean isTriggeringEvent( File activeFile, E event ) {
        if ( !started ) {
            nextCheck = 0L;
            return started = true;
        }

        return super.isTriggeringEvent( activeFile, event );
    };
}

第2次配置lockbax

<appender name="FILE" class="ch.qos.logback.core.rolling.RollingFileAppender">
    <file>${LOGS_DIR}/${FILE_NAME}.log</file>
    <encoder>
        <pattern>%d [%thread] %-5level %logger{50} - %msg%n</pattern>
    </encoder>
    <rollingPolicy class="ch.qos.logback.core.rolling.TimeBasedRollingPolicy">
        <fileNamePattern>${LOGS_DIR}/${FILE_NAME}.%d{yyyy-MM-dd}_%d{HHmmss,aux}.%i.log.zip</fileNamePattern>
        <maxHistory>30</maxHistory>
        <TimeBasedFileNamingAndTriggeringPolicy class="my.StartupSizeTimeBasedTriggeringPolicy">
            <MaxFileSize>250MB</MaxFileSize> 
        </TimeBasedFileNamingAndTriggeringPolicy>
    </rollingPolicy>
</appender>