How do I configure logback to gzip my logs automatically?

Zhuo YING picture Zhuo YING · Jun 1, 2013 · Viewed 21.5k times · Source

i am using logback in my java web appliaction. here's my "logback.xml" file.

<?xml version="1.0" encoding="UTF-8"?>
<configuration debug="false">

    <property name="LOG_DIR" value="/home/ying/.jetty_logs/vehicle" />

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

    <appender name="LAST" class="ch.qos.logback.core.rolling.RollingFileAppender">
        <file>${LOG_DIR}/last.log</file>
        <rollingPolicy class="ch.qos.logback.core.rolling.TimeBasedRollingPolicy">
            <fileNamePattern>last.%d{yyyy-MM}.gz</fileNamePattern>
            <maxHistory>24</maxHistory>
        </rollingPolicy>
        <encoder>
            <pattern>%date:%msg%n</pattern>
        </encoder>
    </appender>

    <logger name="org.springframework" level="WARN" />
    <logger name="org.apache.shiro" level="WARN" />
    <logger name="org.hibernate" level="WARN" />

    <logger name="ying.car.interceptor.AutoLoginInterceptor" additivity="false" level="INFO">
        <appender-ref ref="LAST" />
    </logger>
    <logger name="ying.car.controller.LoginController" additivity="false" level="INFO">
        <appender-ref ref="LAST" />
    </logger>
    <logger name="ying.car.controller.LogoutController" additivity="false" level="INFO">
        <appender-ref ref="LAST" />
    </logger>

    <root level="DEBUG">
        <appender-ref ref="STDOUT" />
    </root>

</configuration>

today is june 1st 2013, all my old logs are overwrited and no *.gz created. somebody help me, please.

Answer

Waheed picture Waheed · Jun 14, 2013

Try to do like this, Hope it will work for you.

<appender name="FILE"
    class="ch.qos.logback.core.rolling.RollingFileAppender">
    <File>${LOGDIR}/filename.log</File>
    <rollingPolicy class="ch.qos.logback.core.rolling.TimeBasedRollingPolicy">
        <!-- rollover daily -->
        <FileNamePattern>${LOGDIR}/file.%d{yyyy-MM-dd}.%i.log.gz
        </FileNamePattern>
        <!-- keep 30 days' worth of history -->
        <MaxHistory>30</MaxHistory>
        <!-- or whenever the file size reaches 10MB -->
        <timeBasedFileNamingAndTriggeringPolicy
            class="ch.qos.logback.core.rolling.SizeAndTimeBasedFNATP">
            <maxFileSize>10MB</maxFileSize>
        </timeBasedFileNamingAndTriggeringPolicy>
    </rollingPolicy>
    <encoder class="ch.qos.logback.classic.encoder.PatternLayoutEncoder">
        <Pattern>%date [%thread] %-5level %logger{36} - %msg%n
        </Pattern>
    </encoder>
</appender>

The above code will compress your file on the day basis or If the log file size exceeds 10MB.

Note : I have added "%i" in filePattern, It will iterate your file name as file1,file2 etc.