views:

247

answers:

1

The Java docs for Logger indicate that the logger name should be based on the class name. Google Guice handles this in BinderImpl.java where it does the following:

return member == null
      ? Logger.getAnonymousLogger()
      : Logger.getLogger(member.getDeclaringClass().getName());

However, since it's getting a new logger for each class, I would lose access to whatever Handler's may have been added to my logger.

What's the best way to handle both having the class name used within the logger and having a standard set of handlers applied?

+1  A: 

The solution actually has nothing to do with Guice, but rather, is based on how the logging classes work in Java.

Loggers are created in a hierarchy, thus, logger x.y.z is a child of x.y, all the way up the chain to the root logger whose name is the empty string. Each logger inherits properties, like its logging level, from its parent.

Thus, in order to set the log level globally (or to set handlers globally), simply set them on the root logger:

LogManager logManager = LogManager.getLogManager();
Logger rootLogger = logManager.getLogger("");
rootLogger.setLevel(Level.FINEST);
rootLogger.addHandler(new ConsoleHandler());

Once that's done, any injected loggers will have their properties derived from the root logger and any parent loggers that may exist. For more information on the basics, see the LogManager documentation.

A config property also exists. Per the LogManager documentation:

A property "config". This property is intended to allow arbitrary configuration code to be run. The property defines a whitespace or comma separated list of class names. A new instance will be created for each named class. The default constructor of each class may execute arbitrary code to update the logging configuration, such as setting logger levels, adding handlers, adding filters, etc.

This implies that there are multiple solutions to the problem as I could have also used a configuration class.

Kaleb Pederson