Did this blog help you solve a problem? Tip me with Bitcoins at: 17dQktcAmU4urXz7tGk2sbuiCqykm3WLs6

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.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!!


Sheraz Ahmed Syed said...

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

Sheraz Ahmed Syed 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

Kai Winter 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.