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. I took his code and in my JUnit test’s @Before method I invoke the log configuration method shown below. Better yet, do this in the @BeforeClass method.
/** * @author MR Head * @author J. Betancourt */ private void initLogging(){ String config = "handlers = java.util.logging.ConsoleHandler" + "\n" + ".level = ALL"+"\n"+"java.util.logging.ConsoleHandler.level = ALL"; 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
- Getting the java.util.logging facilities to log messages of ALL levels…
- java.util.logging.Logger doesn’t respect java.util.logging.Level?
- Java Logging: Configuration
