Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

logback RollingFileAppender rolling at fixed time

A typical logback appender configuration is

<appender name="NAME"
    class="ch.qos.logback.core.rolling.RollingFileAppender">
    <file>FILEPATH.log</file>
    <rollingPolicy class="ch.qos.logback.core.rolling.TimeBasedRollingPolicy">
        <fileNamePattern>FILEPATH.%d{yyyy-MM-dd-HH}.log</fileNamePattern>
        <maxHistory>24</maxHistory>
    </rollingPolicy>
    <encoder>
        <pattern>%msg%n</pattern>
        <charset>UTF-8</charset>
    </encoder>
</appender>

Usually it works fine to me. But I found that it will not split log file as the rollingPolicy specified when there's no log appended to the logger respected.

Please tell me How I can configure it to split log file for every hours even there's no log record for some hours. If there's no log record for any hour, I need logback to create an empty file for that hour.

like image 528
terry Avatar asked Dec 06 '25 03:12

terry


1 Answers

I was with the same problem and I guess logback doesn't able to do it per default.

I found this issue at logback backlog to handle exactly with this: https://jira.qos.ch/browse/LOGBACK-554 and it`s still open.

What I did for now was implement my own rolling appender policy, based on it: https://ronanquillevere.github.io/2015/08/04/rolling-log-15-min.html

You can extend the RollingFileAppender class and override the rollover method, like this:

public class CustomAppender<E> extends RollingFileAppender<E>
{
    private static long start = System.currentTimeMillis();
    private int rollOverTimeInMinutes = 60;

    @Override
    public void rollover()
    {
        long currentTime = System.currentTimeMillis();
        int maxIntervalSinceLastLoggingInMillis = rollOverTimeInMinutes * 60 * 1000;

        if ((currentTime - start) >= maxIntervalSinceLastLoggingInMillis)
        {
            super.rollover();
            start = System.currentTimeMillis();
        }
    }
}

And on logback file xml config, you just set your custom pollicy on appender property:

<appender name="FILE" class="<your-package>.CustomAppender" >
like image 104
Roberto Duessmann Avatar answered Dec 10 '25 08:12

Roberto Duessmann



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!