SLF4J - Logback: How to configure loggers in runtime?

Amr Faisal picture Amr Faisal · Mar 27, 2011 · Viewed 31.4k times · Source

we are using LogBack with our project, I want to configure logger according to some Data Base values, i.e If some DB value is set to true, then logger should use both file and DB appenders, if it's false so logger must use only DB appender,

I also want to preserve using static final loggers, so I won't create a new instance each time logger is called,

so how could I do something like this?

Regards,

Answer

fglez picture fglez · Apr 19, 2011

You should configure Logback programmatically as described in this example.

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) {
       fileAppender.stop();
       fileAppender.setFile("new.log");
       PatternLayout pl = new PatternLayout();
       pl.setPattern("%d %5p %t [%c:%L] %m%n)");
       pl.setContext(lc);
       pl.start();
       fileAppender.setLayout(pl);
       fileAppender.setContext(lc);
       fileAppender.start();
     }
     ... etc    
   }
}