Java RollingFileAppender-class And Method Code Example


Here is an example of how to use the RollingFileAppender class from the logback library to write log messages to a file and automatically rollover the file based on a size limit:

import ch.qos.logback.core.rolling.RollingFileAppender;
import ch.qos.logback.core.rolling.SizeBasedTriggeringPolicy;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

public class MyApp {
    public static void main(String[] args) {
        // create a new logger
        Logger logger = LoggerFactory.getLogger("MyApp");

        // create a new RollingFileAppender
        RollingFileAppender<ILoggingEvent> fileAppender = new RollingFileAppender<>();
        fileAppender.setFile("mylog.log");
        fileAppender.setAppend(true);
        fileAppender.setEncoder(new PatternLayoutEncoder());

        // create a new SizeBasedTriggeringPolicy
        SizeBasedTriggeringPolicy<ILoggingEvent> triggeringPolicy = new SizeBasedTriggeringPolicy<>();
        triggeringPolicy.setMaxFileSize("10MB");

        // set the triggering policy for the RollingFileAppender
        fileAppender.setTriggeringPolicy(triggeringPolicy);
        fileAppender.setRollingPolicy(new TimeBasedRollingPolicy<ILoggingEvent>());

        // start the RollingFileAppender
        fileAppender.start();

        // add the RollingFileAppender to the logger
        logger.addAppender(fileAppender);

        // log some messages
        logger.debug("Debug message");
        logger.info("Info message");
        logger.warn("Warning message");
        logger.error("Error message");
    }
}

In this example, the RollingFileAppender class is used to write log messages to a file and automatically rollover the file based on a size limit.

The setFile method is used to specify the log file, setAppend(true) makes sure that the logs are appended to the file instead of overwriting it and setEncoder is used to specify the layout of the logs.

The SizeBasedTriggeringPolicy class is used to specify the size limit for the log file, in this case, "10MB".

Once the size limit is reached, the RollingFileAppender will create a new log file, and will keep rolling over the log files based on the size limit.