Friday, June 1, 2012

Load a logback.xml Configuration File Programmatically

Today I had a unique situation where I needed to load a logback.xml file programmatically for Logback logging rather than via the standard "from the classpath" way, and here's how I did it. It was quite simple.

The following snippet shows how to load a logging configuration file such as logback.xml programmatically:

LoggerContext context = (LoggerContext) LoggerFactory.getILoggerFactory();
try {

  JoranConfigurator configurator = new JoranConfigurator();
  configurator.setContext(context);
  configurator.doConfigure(logFilePath); // loads logback file
} catch (JoranException je) {
  // StatusPrinter will handle this
} catch (Exception ex) {

  ex.printStackTrace(); // Just in case, so we see a stacktrace

}
StatusPrinter.printInCaseOfErrorsOrWarnings(context); // Internal status data is printed in case of warnings or errors.


Piece of Cake!!

3 comments:

Unknown said...

Question is logfilePath is relative to the system or what must it to be. Do send email at sherazenergetic@yahoo.com

Unknown said...

What must be the value of logFile...is it relative to the system or what it must to be.....Please share the value of the variable

Unknown said...

Your snippet is missing one important call of context.reset() before you are loading the new configuration. Without that call I had the problem of duplicated logging entries because the previous (default logger) wasn't detached.