I am using logback, and I am trying to set the log file name programmatically within my Java program (similar to Setting Logback Appender path programmatically), and I tried to adapt that solution as follows:
In logback-test.xml:
<appender name="FILE" class="ch.qos.logback.core.FileAppender">
<file>log/${log_file_name}.log</file>
...
And then again in my Java program:
String logFileName = "" + System.currentTimeMillis(); // just for example
System.setProperty("log_file_name", logFileName);
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);
However the result is two logs, one full and named as I wanted, e.g., "1319041145343.log", and the other is empty and named "log_file_name_IS_UNDEFINED.log". How do I stop this other empty log file from being created?
Here is what you can do to ignore those extra file creation.Below is the config file
Here is the java part,
I got this from here http://logback.qos.ch/faq.html#sharedConfiguration
To separate/sift log messages to different files depending on a runtime attribute, you might want to use ch.qos.logback.classic.sift.SiftingAppender.
In a nutshell, this allows you to set up a
FileAppender
(or any other appender) with<file>${userid}.log</file>
where${userId}
is substituted based on the MDC (Mapped Diagnostic Context) (e.g.,MDC.put("userid", "Alice");
). See the first link for the complete example.I believe the following to be closer to what you want.
If all you need is to add a timestamp of the log file name, logback already supports the timestamp element. Thus, you actually don't need any custom code at all.
Looks like the logger is initialized twice. First time, probably when the app loads and it couldn't resolve the
${log_file_name}
. If you start the app with-Dlog_file_name=*something*
you can verify this behavior if it creates another log file with the name*something*