Set Java console output to “fine” logging level

While coding a Java module I used java.util.logging output at the INFO level in the code to help development. This info is useful only during development. Are these output statements removed when development is done?

The correct answer is that they should have been logged at the correct level, “debug“, or in java.util.logging’s NIH design, the FINE level. Thing is, the default configuration for console output blocks the FINE level. So, you have to configure the project’s logging appropriately.

This task falls under the develotrivia (related to administrivia) category, the endless tasks that should be easy but draw attention from writing code.

Fortunately I stumbled on a blog post by Michael R. Head that gives an easy way to configure the logger. Essentially it just creates a config string with text that normally would be put in a properties file. I took his example code and created a method that is invoked in the @Before method. Better yet, do this in the @BeforeClass method.

/**
 * Based on code by MR Head
 * @author J. Betancourt
 */
private void initLogging(){
    String config = "\n" + 
       "handlers = java.util.logging.ConsoleHandler" + "\n" + 
       ".level = ALL"+"\n"+
       "java.util.logging.ConsoleHandler.level = FINE" + "\n" +
       "com.sun.level = INFO" + "\n" +
       "javax.level = INFO" + "\n" +
       "sun.level = INFO" + "\n" +
       "";

	InputStream ins = new ByteArrayInputStream(config.getBytes());

	Logger logger = Logger.getLogger(this.class.getName());
	try {
	   LogManager.getLogManager().readConfiguration(ins);
	} catch (IOException e) {
	   logger.log(Level.WARNING, 
	     "Log manager configuration failed: " + e.getMessage(),e);
	}

	logger.fine("Logger initialized");    
	
}

Example Use

@Before
public void setUp() throws Exception {
	initLogging();
	graph = new Graph();
}

BTW, it is not difficult to configure the logger, just point to a configuration properties file using a JVM env variable setting, or point to a log manager class (I tried this, doesn’t work). I think Michael’s method is easier, especially for test driven development (TDD).

Links

Similar Posts:

Creative Commons License
This work is licensed under a Creative Commons Attribution-NonCommercial-NoDerivs 3.0 Unported License.

Leave a Reply

Your email address will not be published. Required fields are marked *