views:

54

answers:

2

I'm trying to set Logback appender path programmatically. (RollingFileAppender with FixedWindowRollingPolicy to be exact)

I'm doing this because I want to enable my users to set the log path in a preference dialog (Eclipse RCP)

I've tried something like this, but I doesn't change the log path from what's defined in the configuration file:

Logger logback_logger = (ch.qos.logback.classic.Logger)LoggerFactory
   .getLogger(org.slf4j.Logger.ROOT_LOGGER_NAME);
RollingFileAppender<ILoggingEvent> rfappender = 
   (RollingFileAppender<ILoggingEvent>)logback_logger.getAppender("FILE");
rfappender.setFile(newFile);
FixedWindowRollingPolicy rollingPolicy = 
   (FixedWindowRollingPolicy)rfappender.getRollingPolicy();
rollingPolicy.setFileNamePattern(newPattern);
A: 

Looking at the Logback code, I have found a workaround:

rollingPolicy.stop();
rfappender.stop();
rollingPolicy.start();
rfappender.start();

This causes Logback to use the new definitions. It still feels like a workaround, though.

yshalbar
+1  A: 

Using system properties and reloading the configuration file seems cleaner:

change the logback.xml file:

<file>${log_path:-}myfile.log</file>
....
<FileNamePattern>${log_path:-}myfile.%i.log</FileNamePattern>

This will set the default location to the working directory. Then, use:

System.setProperty("log_path", my_log_path);

//Reload:
LoggerContext lc = (LoggerContext) LoggerFactory.getILoggerFactory();
ContextInitializer ci = new ContextInitializer(lc);
lc.reset();
try {
  //I prefer autoConfig() over JoranConfigurator.doConfigure() so I wouldn't need to find the file myself.
  ci.autoConfig(); 
} catch (JoranException e) {
  // StatusPrinter will try to log this
  e.printStackTrace();
}
StatusPrinter.printInCaseOfErrorsOrWarnings(lc);
yshalbar