How to create logback Loggers dynamically/Pragmatically

Code snippet

import ch.qos.logback.classic.Logger;
import ch.qos.logback.classic.LoggerContext;
import ch.qos.logback.classic.encoder.PatternLayoutEncoder;
import ch.qos.logback.core.rolling.RollingFileAppender;
import ch.qos.logback.core.rolling.TimeBasedRollingPolicy;
import java.io.File;
import org.slf4j.LoggerFactory;

private void demo() {
    LoggerContext context = (LoggerContext) LoggerFactory.getILoggerFactory();
    logger = context.getLogger("dynamic_logger");

    // Don't inherit root appender
    logger.setAdditive(false);

    RollingFileAppender rollingFile = new RollingFileAppender();
    rollingFile.setContext(context);
    rollingFile.setName("dynamic_logger_fileAppender");

    // Optional
    rollingFile.setFile("/log"
            + File.separator + "msg.log");
    rollingFile.setAppend(true);

    // Set up rolling policy
    TimeBasedRollingPolicy rollingPolicy = new TimeBasedRollingPolicy();
    rollingPolicy.setFileNamePattern("/log"
            + File.separator + "%d{yyyy-MM,aux}"
            + File.separator + "msg_%d{yyyy-MM-dd_HH-mm}.txt");

    rollingPolicy.setParent(rollingFile);
    rollingPolicy.setContext(context);
    rollingPolicy.start();

    // set up pattern encoder
    PatternLayoutEncoder encoder = new PatternLayoutEncoder();
    encoder.setContext(context);
    encoder.setPattern("%msg%n");
    encoder.start();

    rollingFile.setRollingPolicy(rollingPolicy);
    rollingFile.setEncoder(encoder);
    rollingFile.start();

    // Atach appender to logger
    logger.addAppender(rollingFile);

}

Logback.xml

<?xml version="1.0" encoding="UTF-8"?>
<configuration>
  <statusListener class="ch.qos.logback.core.status.OnConsoleStatusListener"/>
  <appender name="STDOUT" class="ch.qos.logback.core.ConsoleAppender">
    <encoder>
      <pattern>%d [%thread] %-5level  %logger{35} - %msg%n</pattern>
    </encoder>
  </appender>
  <appender name="fileAppender" class="ch.qos.logback.core.rolling.RollingFileAppender">
    <file>${jetty.home}/logs/jetty.log</file>
    <rollingPolicy class="ch.qos.logback.core.rolling.TimeBasedRollingPolicy">
      <!-- daily rollover -->
      <fileNamePattern>/logs/jetty_%d{yyyy-MM-dd}.log</fileNamePattern>
      <!-- keep 30 days' worth of history -->
      <maxHistory>30</maxHistory>
    </rollingPolicy>
    <append>true</append>
    <encoder>
      <pattern>%d [%thread] %-5level  %logger{35} - %msg%n</pattern>
    </encoder>
  </appender>

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

What does it do?

This code snippet creates a logback Logger named "dynamic_logger" using RollingFileAppender. Log file location is "/log", and it's rolled every minute ("%d{yyyy-MM-dd_HH-mm}").

More info about rolling policy: http://logback.qos.ch/manual/appenders.html#TimeBasedRollingPolicy

rollingFile.setFile(...) is optional, if not set, FileNamePattern inside rolling policy will be used.

By default, all loggers will "inherit" the appenders from ROOT logger. Use logger.setAdditive(false) to disable this behavior. Otherwise, in the case above, the log message will appear in "dynamic_logger_fileAppender", "fileAppender", and "STDOUT".

Comments !