ichttt
ichttt

Reputation: 95

Java Util Logging set FileHandler global

I want to log everything with JUL and set up a FileHandler to write everything to a log file, however, it only logs the content which is in the same class as the FileHandler. How do I set FileHandler global without using a config file?

Upvotes: 0

Views: 561

Answers (1)

Palamino
Palamino

Reputation: 791

You can walk the Logger parents, remove any other handlers your find and call logger.setUserParentHandlers(true) until logger.getParent() returns null. That tells you you have found the root Logger instance, upon which you call logger.addHandler(myOwnHandler). You may also want to call logger.setLevel(...) on each logger to ensure your handler sees all of the logging activity. Here is sample code:

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

static {
    Logger logger = LOGGER.getParent();
    while(logger != null) {
        Handler[] handlers = logger.getHandlers();
        if(handlers != null) {
            for(Handler handler : handlers) {
                logger.removeHandler(handler);
            }
        }

        if(logger.getParent() == null) {
            logger.addHandler(SystemErrHandler.newInstance());
        }
        else {
            logger.setUseParentHandlers(true);
        }

        if(logger.getName().startsWith("my.sample.package")) {
            logger.setLevel(Level.ALL);
        }
        logger = logger.getParent();
    }
}

Upvotes: 1

Related Questions