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 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.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 ;)
    // Set root logger level

  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.finest("Now finest is logged as well.");

IT consultant and Java specialist at CAG Contactor.

Publicerad i Uncategorized


WP to LinkedIn Auto Publish Powered By :