Configure java.util.logging programmatically

Sometimes it is useful to configure the java.util.logging programmatically, e.g, in unit test drivers or in a proprietary management interface.

However, the default logging settings (see logging.properties in your java installation) will only let INFO level loggings through. The reason is that per default one will have a) global log level = INFO; b) a ConsoleHandler configured with level=INFO.

To enable the FINEST level one must set the level on the handler of the root logger. In addition one might alter the level of the root logger, which will be inherited by all other loggers.

The following example illustrates this:

import java.io.IOException;
import java.util.logging.*;
public class ConfigureLogging {
  static {
    // Get the root logger
    Logger rootLogger = Logger.getLogger("");
    for(Handler handler : rootLogger.getHandlers()) {
      // Change log level of default handler(s) of root logger
      // The paranoid would check that this is the ConsoleHandler ;)
      handler.setLevel(Level.FINEST);
    }
    // Set root logger level
    rootLogger.setLevel(Level.FINE);
  }

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

  public static void main(String argv[]) throws IOException {
    logger.finest("Won't be logged since root logger is configured with FINE.");
    logger.fine("Will be logged.");

    // Set level on local logger as well
    logger.setLevel(Level.FINEST);
    logger.finest("Now finest is logged as well.");
  }
}

IT consultant and Java specialist at CAG Contactor.

Publicerad i Uncategorized

Kategorier

WP to LinkedIn Auto Publish Powered By : XYZScripts.com