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);
Using system properties and reloading the configuration file seems cleaner:
change the logback.xml file:
This will set the default location to the working directory. Then, use:
Once you programmatically configure your appender, you need invoke its
start()
method. If the appender has sub-components, invokestart()
on the sub-components first. You then add the appender to the logger of your choice.Here is an example:
The above code is the programmatic expression of the steps taken by the logback's XML configurator, i.e. Joran, when it parses the RollingFixedWindow.xml file.
Looking at the Logback code, I have found a workaround:
This causes Logback to use the new definitions. It still feels like a workaround, though.