logging-log4j-user mailing list archives

Site index · List index
Message view « Date » · « Thread »
Top « Date » · « Thread »
From Michael Erskine <michael.ersk...@ketech.com>
Subject RE: static log4j configuration statement
Date Wed, 10 Sep 2008 14:20:18 GMT
> I use standard static code to include the log4j configuration:
> static {
>     PropertyConfigurator.configure("file"));
> }
> But this code is not always executed, depending on if the class in which
> this is included particpates in execution. But if I add this statment to
> other classes too,
> I sooner or later get double-messages as two classes with this statement
> are used. Then I need to manually remove the code in one of them to
> achieve proper logging.
> How this is done right? I just want to have this configuration stated
> once and applicable to the whole project.

Hi Sebastian,

What I tend to do is have a class to do something similar but first check whether already
configured: my class is called LogConfigureCheck and is used in a static block for all my
JUnit tests thus...

    static {

...and here follows a version of the class suitable for redistribution.

Michael Erskine

import org.apache.log4j.ConsoleAppender;
import org.apache.log4j.Logger;
import org.apache.log4j.PatternLayout;

 * Occasionally we find a JUnit test suite or test case class that tests classes
 * that use log4j but for whatever reason log4j is not configured. We want to
 * avoid log4j being configured multiple times as this adds its own problems!
 * The aim here is to enforce that log4j is configured once and only once with
 * typical but useful features.
 * @author Michael Erskine (msemtd)
public class LogConfigureCheck {
    public static void check() {
        // One indicator of log4j not being configured is the lack of appenders
        // for the root logger. So...
        if (!Logger.getRootLogger().getAllAppenders().hasMoreElements()) {
            // Here we could just use BasicConfigurator.configure()
            // but the layout is not as useful as it could be - here we do
            // essentially the same but with a better layout...
                new ConsoleAppender(new PatternLayout(
                    "%-5p %d{HH:mm:ss.SSS} %c [%t] %m%n")));

To unsubscribe, e-mail: log4j-user-unsubscribe@logging.apache.org
For additional commands, e-mail: log4j-user-help@logging.apache.org

View raw message