27

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,

Amr Faisal
  • 2,004
  • 6
  • 27
  • 36

2 Answers2

19

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    
   }
}
fglez
  • 8,422
  • 4
  • 47
  • 78
  • This is what we used to do with logback 1.0.6, but in 1.1.7 it doesn't work anymore: a stopped appender cannot be reused. See http://logback.qos.ch/apidocs/ch/qos/logback/core/OutputStreamAppender.html#stop() – Nicola Musatti Oct 28 '16 at 08:34
1

Is there a specific reason behind reading the configuration property from the database? One suggestion would be to use JNDI. Logback can read JNDI configured values using the tag.

Andy Dufresne
  • 6,022
  • 7
  • 63
  • 113