简体   繁体   English

我可以根据系统变量打开/关闭CONSOLE日志记录吗?

[英]Can I turn CONSOLE logging on/off depending on a system variable?

We maintain an application wide system variable [debug=true|false], I want to disable all CONSOLE appenders in log4j upon startup when the system variable debug is false. 我们维护一个应用程序范围的系统变量[debug = true | false],我想在系统变量debug为false时在启动时禁用log4j中的所有CONSOLE appender。

Is the best way just a programatic scan of the appenders? 是最好的方式只是对appenders的程序扫描? Or is there a more elegant approach that I don't know about perhaps? 或者是否有一种我不知道的更优雅的方法?

Any primer on scanning the appenders would be welcome also if that's the right approach. 如果这是正确的方法,任何有关扫描appender的入门书也会受到欢迎。

I would write a special filter for the console appender. 我会为控制台appender编写一个特殊的过滤器。 Along the line of 沿着这条线

<appender name="stdout" class="org.apache.log4j.ConsoleAppender">
    <layout class="org.apache.log4j.TTCCLayout">
        <param name="ConversionPattern" value="%d...m%n"/>
    </layout>
    <filter class="OnDebugOnly"/>
</appender>

With the Filter defined as follows 使用Filter定义如下

import org.apache.log4j.spi.Filter;
import org.apache.log4j.spi.LoggingEvent;

public class OnDebugOnly extends Filter {

    static boolean debug;

    @Override
    public int decide(LoggingEvent event) {
        return ( debug ? Filter.NEUTRAL : Filter.DENY ) ;
    }
}

Of course this needs adjustments. 当然这需要调整。 Like where debug is defined and how it is accessed. 就像定义调试的位置以及访问方式一样。
The Neutral is just in case someone adds another filter... 中立是为了防止有人添加另一个过滤器......
Plus the layout is just mine, use your preferred layout here. 加上布局就是我的,在这里使用您喜欢的布局。
Caveat. 警告。 I did not test it ;-) 我没有测试它;-)

Have you looked into setting up a .properties file for log4j? 您是否考虑过为log4j设置.properties文件? You can configure log4j to send logging messages to a file, turn off sending log messages to the console for info, warn, etc. You can even configure it on a per class basis if needed. 您可以配置log4j以将日志消息发送到文件,关闭向控制台发送日志消息以获取信息,警告等。如果需要,您甚至可以按类别进行配置。 If you go to this site and navigate to the Configuration section, it should tell you what you need to know. 如果您访问此站点并导航到“配置”部分,它应该告诉您需要了解的内容。

http://logging.apache.org/log4j/1.2/manual.html http://logging.apache.org/log4j/1.2/manual.html

Hopefully this answers your question. 希望这能回答你的问题。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM