登录-在启动时不要创建空的日志文件 [英] Logback - do not create empty log files at startup

查看:92
本文介绍了登录-在启动时不要创建空的日志文件的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个项目,其中包含许多具有自己的日志记录的工具"类.这些日志文件是在应用程序启动时创建的,但是在使用之前一直为空.

是否可以告诉logback在启动时不应该创建空文件?但是只有在使用它们时?

我找不到有关此主题的信息.谢谢!

解决方案

在Logback的FilAppender中,没有对延迟/按需创建日志文件的官方支持.

但是,有些已知的配置替代方法可能会达到相同的结果.有关更多详细信息,请参见登录功能请求202"FileAppender应允许创建惰性文件" ./p>

我个人最喜欢的是使用LazyFileOutputStream和FileAppender的自定义实现的变体.可以找到 LazyFileOutputStream的有效实现.在Alessio Pollero的log4j-additions部分中.

LazyFileappender代码非常简单:

 公共类LazyFileAppender< E>扩展FileAppender< E>{@Overridepublic void openFile(String file_name)引发IOException {lock.lock();尝试 {文件文件=新文件(文件名);布尔结果= FileUtil.createMissingParentDirectories(file);如果(!结果){addError(无法为[" + file.getAbsolutePath()+]"创建父目录);}LazyFileOutputStream lazyFos =新的LazyFileOutputStream(file,append);setOutputStream(lazyFos);} 最后 {lock.unlock();}}} 

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 FilAppender.

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

}

这篇关于登录-在启动时不要创建空的日志文件的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆