I have a project with a lot of 'tool' classes that have their own logging. Those logfiles are created at startup of the application, but remain empty, until used.
Is it possible to tell logback that empty files should not be created at startup? But only when they are being used?
Somehow I don't find information on this topic. Thanks!
During startup, logback tries to locate logback-test.xml or logback.xml in the classpath, in the same order. If the file is found, it configures itself using the provided configuration file.
This is Logback's default behavior; if it can't find a configuration file, it creates a ConsoleAppender and associates it with the root logger. 6.1. Locating Configuration Information A configuration file can be placed in the classpath and named either logback.xml or logback-test.xml. Here's how Logback will attempt to find configuration data:
In the previous examples, we were using the 11-line configuration file we created in section 4 to print log messages to the console. This is Logback's default behavior; if it can't find a configuration file, it creates a ConsoleAppender and associates it with the root logger. 6.1.
For Logback configuration through XML, Logback expects a Logback.xml or Logback-test.xml file in the classpath. In a Spring Boot application, you can put the Logback.xml file in the resources folder. If your Logback.xml file is outside the classpath, you need to point to its location using the Logback.configurationFile system property, like this.
There is no official support for lazy/on-demand creation of log files in Logback's FileAppender
.
However there are some known configuration workarounds that may achieve the same result. For more details see the Logback feature request 202 "FileAppender should permit lazy file creation".
My personal favorite is the variant using the LazyFileOutputStream and a custom implementation of a FileAppender. A working implementation of an LazyFileOutputStream can be found in Alessio Pollero's log4j-additions section.
An the LazyFileappender code is very simple:
public class LazyFileAppender<E> extends FileAppender<E> {
@Override
public void openFile(String file_name) throws IOException {
lock.lock();
try {
File file = new File(file_name);
boolean result = FileUtil.createMissingParentDirectories(file);
if (!result) {
addError("Failed to create parent directories for [" + file.getAbsolutePath() + "]");
}
LazyFileOutputStream lazyFos = new LazyFileOutputStream(file, append);
setOutputStream(lazyFos);
} finally {
lock.unlock();
}
}
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With