Setting the ConsoleHandler’s Level


I used to create a logger like this.

class MyClass {

    private static final Logger LOGGER =
        Logger.getLogger(MyClass.getName());

    static {
        LOGGER.setLevel(Level.OFF); // turn it on when you're debugging
    }

    public MyClass() {
        super();
        LOGGER.info("I'm just created.");
    }
}

But when I tried to debug with Level.FINER I simply found it doesn’t work.

class MyClass {

    private static final Logger LOGGER =
        Logger.getLogger(MyClass.getName());

    static {
        //LOGGER.setLevel(Level.OFF); // turn it on when you're debugging
        LOGGER.setLevel(Level.FINEST);
    }

    public MyClass() {
        super();
        LOGGER.info("I'm just created.");
        LOGGER.finest("And this is a finest level"); // not printed
    }
}

The problem is the ConsoleHandler which is attached to the root logger (not the global logger) has its own Level for handling those LogRecords from the LOGGER.

static void setConsoleHandlerLevel(final Logger logger, final Level level) {

    if (logger.getUseParentHandlers()) {
        final Logger parent= logger.getParent();
        if (parent != null) {
            setConsoleHandlerLevel(parent, level);
            return;
        }
    }

    for (Handler handler : logger.getHandlers()) {
        if (handler instanceof ConsoleHandler) {
            handler.setLevel(level);
            return;
        }
    }
}

Not I can change the level like this.

class MyClass {

    private static final Logger LOGGER =
        Logger.getLogger(MyClass.getName());

    static {

        final boolean useParenthandlers = true; // change this as you want
        LOGGER.setUseParentHandlers(useParentHandlers);
        if (!useParentHandlers) {
            LOGGER.addHandler(new ConsoleHandler());
        }

        final Level level = Level.FINEST; // change this as you want.
        LOGGER.setLevel(level);
        setConsoleHandlerLevel(logger, logger.getLevel());
    }
}
Advertisements

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s