[logback-user] dynamically creating/destroying logging appenders
Ceki Gulcu
ceki at qos.ch
Fri Aug 7 23:30:27 CEST 2009
Bridges, Ed (Citco) wrote:
> Just so that we're clear, what I'm talking about is a legacy PSVM
> program that gets invoked in batch. What I've been tasked with is
> having each individual execution get written to its own file. The
> SiftingAppender seems to not fit since there is no difference in the
> different log messages except the time of execution, and the
> executions would happen sequentially (no parallel executions since the
> legacy application is not thread safe).
SiftingAppender can act on any criteria you chose, including the name
or id of the current thread. In other words, SiftingAppender could
handle you problem but is perhaps an overkill for the problem you are
facing.
Here is a simple solution which would work with logback 0.9.16 (the latest release):
Here is a sample config file:
<configuration>
<appender name="FILE" class="ch.qos.logback.core.FileAppender">
<File>psvm-${TIMESTAMP}.log</File>
<Append>false</Append>
<layout>
<Pattern>%-4relative [%thread] %-5level %logger{35} - %msg%n</Pattern>
</layout>
</appender>
<root level="debug">
<appender-ref ref="FILE" />
</root>
</configuration>
Note the TIMESTAMP property. It needs to be set before configuring logback. Here
is sample code:
import ch.qos.logback.classic.LoggerContext;
import ch.qos.logback.classic.joran.JoranConfigurator;
import ch.qos.logback.core.joran.spi.JoranException;
class MyClass ... {
void loadTimeStampedConfiguration() {
LoggerContext lc = (LoggerContext) LoggerFactory.getILoggerFactory();
lc.putProperty("TIMESTAMP", "any string value, e.g new Date().toString()");
JoranConfigurator configurator = new JoranConfigurator();
configurator.setContext(lc);
lc.reset();
configurator.doConfigure("path/to/your/logback.xml configuration file");
}
}
That's it, you are done.
In the next version of logback, the time stamp will be automatically
available, so you won't need to write any code.
>
> So what I'm looking for is that each execution a new log file would be
> created depending on some parameters passed in and a timestamp, and
> then after the execution is completed no more writes would go to that
> log file.
I hope the above answers your question.
--
Ceki Gülcü
Logback: The reliable, generic, fast and flexible logging framework for Java.
http://logback.qos.ch
More information about the Logback-user
mailing list