[logback-dev] programmatic configuration

Ceki Gulcu ceki at qos.ch
Sat Feb 28 13:05:41 CET 2009

Heelo Cheenu,

You can configure logback programmatically which is exactly what Joran 
(logback's configuration framework) does when it reads configuration files.

The log4j example you provide would problay need to be modified as follows:

import org.slf4j.LoggerFactory;

import ch.qos.logback.classic.Logger;
import ch.qos.logback.classic.LoggerContext;
import ch.qos.logback.classic.PatternLayout;
import ch.qos.logback.classic.spi.LoggingEvent;
import ch.qos.logback.core.FileAppender;

public class Main {

   public static void main(String[] args) {
      Logger logger = (Logger) LoggerFactory.getLogger("abc.xyz");

     LoggerContext lc = (LoggerContext) LoggerFactory.getILoggerFactory();
     FileAppender<LoggingEvent> fileAppender =
                       (FileAppender<LoggingEvent>) logger.getAppender("file");
     if(fileAppender != null) {
       PatternLayout pl = new PatternLayout();
       pl.setPattern("%d %5p %t [%c:%L] %m%n)");
     ... etc	

Logback offers a much more convenient alternative in the form of variable 
substitution. See also [1,2,3] below.

You could set the name of the logging file as a java system property at 
application launch, in which case you would not need to do any programmatic 
configuration. You could also set a property programmatically as shown in [2].

[1] http://logback.qos.ch/manual/configuration.html#variableSubstitution
[2] http://logback.qos.ch/faq.html#sharedConfiguration
[3] http://logback.qos.ch/faq.html#overrideFromCL


Cheenu wrote:
> Is there a way to programmatically configure logback without using any 
> config file at all.
> I saw http://logback.qos.ch/xref/chapter3/MyApp3.html
> and that is still configuring using a config file.
> Use-case: multiple invocations of same app (with same classpath) needs to
> log to different file appenders, possibly with different patterns.
> Hence, need facility to dynamically configure these at runtime (at startup).
> In log4j, I can do this using
> Logger logger = Logger.getLogger("abc.xyz");
> FileAppender fileAppender = (FileAppender)logger.getAppender("file");
> if(fileAppender != null) {
>   fileAppender.setFile("new.log");
>   fileAppender.setLayout(new PatternLayout("%d{ISO8601} %5p %t [%c:%L] 
> %m%n"));
>   fileAppender.activateOptions();
> }
> How do I do similar thing in logback?
> Thanks
> Cheenu
Ceki Gülcü
Logback: The reliable, generic, fast and flexible logging framework for Java.

More information about the logback-dev mailing list