java 如何配置 log4j 以启用/禁用日志记录到文件?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/11145887/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-10-31 03:58:14  来源:igfitidea点击:

How to configure log4j to enable/disable logging to a file?

javalog4j

提问by Eric B.

I've written up a small console utility. Throughout the application, I have used slf4j/log4j to log debug, trace, info statements to the console as I was developing it. Now that I am done development and want to release it, I would like to disable all output to the console except for a couple of specific loggers and send all the remaining loggers to a text file.

我已经编写了一个小型控制台实用程序。在整个应用程序中,我在开发过程中使用 slf4j/log4j 将调试、跟踪、信息语句记录到控制台。现在我已经完成了开发并想要发布它,我想禁用除了几个特定记录器之外的所有输出到控制台,并将所有剩余的记录器发送到一个文本文件。

In theory, this should be fairly easy. I have created 2 appenders (one ConsoleAppender and one FileAppender). I have assocaited the ConsoleAppender with the specific loggers want on the Console and the FileAppender at the Root level. This works fine.

理论上,这应该相当容易。我创建了 2 个 appender(一个 ConsoleAppender 和一个 FileAppender)。我已将 ConsoleAppender 与控制台上所需的特定记录器和根级别的 FileAppender 相关联。这工作正常。

My issue now, is if I want to completely disable the FileAppender, I cannot figure out how to do it. If I add a DenyAllFilter to the FileAppender, it will prevent anything from being written to the file, but the file is still created. If I remove the FileAppender from the ROOT logger, I get Log4J writting to StdErr:

我现在的问题是,如果我想完全禁用 FileAppender,我不知道该怎么做。如果我将 DenyAllFilter 添加到 FileAppender,它将阻止任何内容写入文件,但仍会创建文件。如果我从 ROOT 记录器中删除 FileAppender,我会得到 Log4J 写入 StdErr:

log4j:WARN No appenders could be found for logger (org.springframework.context.support.ClassPathXmlApplicationContext).
log4j:WARN Please initialize the log4j system properly.
log4j:WARN See http://logging.apache.org/log4j/1.2/faq.html#noconfig for more info.

If I set the ROOT level to OFF, the individual loggers that I have set custom debug levels to still output.

如果我将 ROOT 级别设置为 OFF,我设置了自定义调试级别的各个记录器仍会输出。

If I set the LoggerRepository Level to OFF, then all loggers (those I want to go to STDOUT and the File) are all shut off.

如果我将 LoggerRepository Level 设置为 OFF,那么所有记录器(那些我想转到 STDOUT 和文件的记录器)都将关闭。

Is there any way to do this easily? Ideally, I want to be able to disable the file appender altogether, however provide a command line switch to enable it if desired.

有没有办法轻松做到这一点?理想情况下,我希望能够完全禁用文件附加程序,但是如果需要,可以提供一个命令行开关来启用它。

<?xml version="1.0" encoding="UTF-8" ?>
<!DOCTYPE log4j:configuration SYSTEM "log4j.dtd">
<log4j:configuration xmlns:log4j='http://jakarta.apache.org/log4j/'>

    <appender name="STDOUT" class="org.apache.log4j.ConsoleAppender">
        <layout class="org.apache.log4j.PatternLayout">
            <param name="ConversionPattern" value="%d{ISO8601} %-5p %c{5} - %X{messageId} - %m%n" />
<!--            <param name="ConversionPattern" value="%m%n" /> -->
        </layout>
    </appender>

    <appender name="LOGTXT" class="org.apache.log4j.FileAppender">
        <param name="file" value="lss-client.log" />
        <param name="append" value="false" />
        <layout class="org.apache.log4j.PatternLayout">
            <param name="ConversionPattern" value="%d{ISO8601} %-5p %c{5} - %X{messageId} - %m%n" />
        </layout>
<!--        <filter class="org.apache.log4j.varia.DenyAllFilter"/> -->
    </appender>

    <!-- Spring Loggers -->
    <logger name="org.springframework">
        <level value="INFO" />
    </logger>

    <logger name="org.springframework.ws.client.MessageTracing.sent">
        <level value="TRACE" />
    </logger>   

    <logger name="org.springframework.ws.client.MessageTracing.received">
        <level value="TRACE" />
    </logger>   

    <logger name="com.cws.cs.Client" >
        <level value="INFO" />
        <appender-ref ref="STDOUT" />
    </logger>

    <root>
        <level value="INFO" />
        <appender-ref ref="LOGTXT" /> 
    </root>
</log4j:configuration>

Thanks!

谢谢!

Eric

埃里克

回答by FGreg

Pretty sure Slf4J/Log4J creates the log file immediately when you configure a FileAppender.

很确定 Slf4J/Log4J 在您配置FileAppender.

I think your best bet here is to have 2 different and complete Log4J configurations and pick which one you load at startup based on your command line parameter.

我认为最好的办法是拥有 2 种不同且完整的 Log4J 配置,然后根据命令行参数选择在启动时加载的一种。

In PseudoCode:

在伪代码中:

public static void main(String[] args){
    //if log to file arg = true
        DOMConfigurator.configure("logToFile.log4j.xml");
    //else
        DOMConfigurator.configure("logToConsoleOnly.log4j.xml");
}

Edit

编辑

Furthermore, if you don't like the idea of maintaining two configuration files. You could create one configuration with the common components (probably the spring stuff and w/e else) and then based on your parameter, programatically configure the FileAppender:

此外,如果您不喜欢维护两个配置文件的想法。您可以使用通用组件(可能是弹簧组件和其他组件)创建一个配置,然后根据您的参数,以编程方式配置FileAppender

public static void main(String[] args){

    DOMConfigurator.configure("log4j.xml");
    //if log to file arg = true{
        // Define layout
        PatternLayout layout = new PatternLayout();
        layout.setConversionPattern("%d{ISO8601} %-5p %c{5} - %X{messageId} - %m%n");

        // Create appender
        FileAppender appender = new FileAppender();
        appender.setFile("lss-client.log");
        appender.setLayout(layout);
        appender.activateOptions();

        // Get root logger and add appender.
        log = Logger.getRootLogger();
        log.setLevel(Level.INFO);
        log.addAppender(appender);
    }
}