Note that there are some explanatory texts on larger screens.

plurals
  1. PO
    text
    copied!<p>Once you programmatically configure your appender, you need invoke its <code>start()</code> method. If the appender has sub-components, invoke <code>start()</code> on the sub-components first. You then add the appender to the logger of your choice.</p> <p>Here is an example:</p> <pre><code>import ch.qos.logback.classic.Logger; import ch.qos.logback.classic.encoder.PatternLayoutEncoder; import ch.qos.logback.core.rolling.FixedWindowRollingPolicy; import ch.qos.logback.core.rolling.RollingFileAppender; import ch.qos.logback.core.rolling.SizeBasedTriggeringPolicy; import ch.qos.logback.core.util.StatusPrinter; import org.slf4j.LoggerFactory; import ch.qos.logback.classic.LoggerContext; public class Main { public static void main(String[] args) { LoggerContext loggerContext = (LoggerContext) LoggerFactory.getILoggerFactory(); RollingFileAppender rfAppender = new RollingFileAppender(); rfAppender.setContext(loggerContext); rfAppender.setFile("testFile.log"); FixedWindowRollingPolicy rollingPolicy = new FixedWindowRollingPolicy(); rollingPolicy.setContext(loggerContext); // rolling policies need to know their parent // it's one of the rare cases, where a sub-component knows about its parent rollingPolicy.setParent(rfAppender); rollingPolicy.setFileNamePattern("testFile.%i.log.zip"); rollingPolicy.start(); SizeBasedTriggeringPolicy triggeringPolicy = new ch.qos.logback.core.rolling.SizeBasedTriggeringPolicy(); triggeringPolicy.setMaxFileSize("5MB"); triggeringPolicy.start(); PatternLayoutEncoder encoder = new PatternLayoutEncoder(); encoder.setContext(loggerContext); encoder.setPattern("%-4relative [%thread] %-5level %logger{35} - %msg%n"); encoder.start(); rfAppender.setEncoder(encoder); rfAppender.setRollingPolicy(rollingPolicy); rfAppender.setTriggeringPolicy(triggeringPolicy); rfAppender.start(); // attach the rolling file appender to the logger of your choice Logger logbackLogger = loggerContext.getLogger("Main"); logbackLogger.addAppender(rfAppender); // OPTIONAL: print logback internal status messages StatusPrinter.print(loggerContext); // log something logbackLogger.debug("hello"); } } </code></pre> <p>The above code is the programmatic expression of the steps taken by the logback's XML configurator, i.e. Joran, when it parses the <a href="https://github.com/qos-ch/logback/blob/master/logback-examples/src/main/resources/chapters/appenders/conf/logback-RollingFixedWindow.xml" rel="noreferrer">RollingFixedWindow.xml</a> file. </p>
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload