Search This Blog

Wednesday, February 18, 2015

Getting java.util.logging to work with JUnit

In my development I normally create the JUnit test cases, but had trouble getting the java.util.logging statement to activate in the code I was testing.  I discovered a couple articles on the web and pieced them together for a solution.

As a reference, here is how I normally implement logging, with my OIM Flat File Connector XMLParser as the class:

import java.util.logging.*;

public class FlatFileXMLParser implements FlatFileParser {
    private static final Logger logger = 

        Logger.getLogger(FlatFileXMLParser.class.getName());

public void parse(File flatFile, FlatFileRecordHandler recordHandler,
                  ParserConfig config) throws Exception {
  String methodName="parse";
  logger.logp(Level.FINE, getClass().getName(), methodName,

    "FF-XMLP-001 entering");

Some explanation:
1) I use java.util.logging and never use log4j.
2) I use logp - never anything else.  One statement=commonality
3) I define String methodName to provide the method name in every module.
4) I add tags so that I can grep on the tags.  Each statement gets a tag.
5) Increment the numbers in the method and skip to next 100 on next method.
6) Debug statements as Level.FINE, use good judgement.

When I attempt to test these code modules I found that the logging was not being generated.  I found a great writeup and took most of this from it.  What I did was put the following into the JUnit class - not in the functional class:

public class AppTest extends TestCase {
  static {
    Logger rootLogger = Logger.getLogger("");
    System.setProperty("java.util.logging.SimpleFormatter.format",

           "[%1$tF %1$tr] [%2$s] %4$s: %5$s %n");
    for(Handler handler : rootLogger.getHandlers()) {
      handler.setLevel(Level.FINEST);
      handler.setFormatter(new SimpleFormatter());
    }
    rootLogger.setLevel(Level.FINEST);
  }


After this is the constructor and the test methods.  The logger will record the details to the output screen and you can track your code.

Good luck testing !!

No comments:

Post a Comment