开发者

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

开发者 https://www.devze.com 2023-02-06 23:57 出处:网络
We maintain an application wide system variable [debug=true|false], I want to d开发者_Go百科isable all CONSOLE appenders in log4j upon startup when the system variable debug is false.

We maintain an application wide system variable [debug=true|false], I want to d开发者_Go百科isable all CONSOLE appenders in log4j upon startup when the system variable debug is false.

Is the best way just a programatic scan of the 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.


I would write a special filter for the console 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

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

Hopefully this answers your question.

0

精彩评论

暂无评论...
验证码 换一张
取 消