Tagged: logging

defining a private logger in a class


I used to define private class loggers like this.

class MyClass {

    private static final Logger logger = Logger.getLogger(
        MyClass.class.getName());
}

Nothing’s wrong, anyway. Even re-factoring problems, such as renaming the class, have been gone since I started using IDEs.
And yet, here comes a new way which could be said somewhat more portable with Java 7.

class MyClass {

    private static final Logger logger = Logger.getLogger(
        MethodHandles.lookup().lookupClass().getCanonicalName());
}
Advertisements

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());
    }
}