質問

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!

役に立ちましたか?

解決

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();
        }
    }

}
ライセンス: CC-BY-SA帰属
所属していません StackOverflow
scroll top