How do I do a conditional logging?

When logging some messages in our application the purpose could be creating a
log for debugging purposes. To minimize the impact of these debug messsage we can
use a conditional logging. To do this we need to wrap each call to the logger method
with a Logger.isLoggable(Level level) check.

The check will ensure that only logs with the appropriate level will be logged
into our application logs. This will automate the on and off our application log
without touching the code.

package org.kodejava.example.util.logging;

import java.util.logging.Logger;
import java.util.logging.Level;
import java.util.Date;

public class ConditionalLogging {
    private Logger logger = Logger.getLogger(ConditionalLogging.class.getName());

    public static void main(String[] args) {
        ConditionalLogging demo = new ConditionalLogging();
        demo.executeMethod();
    }

    //
    // In this method we will check if the Logger level is equals to
    // Level.INFO before we do the real logging. This will minimize
    // the impact of logging if in the next time we increate the level
    // to Level.WARNING or Level.SEVERE so that these message will not
    // logged anymore.
    //
    public void executeMethod() {
        if (logger.isLoggable(Level.INFO)) {
            logger.info("Entering executeMethod() at : " + new Date());
        }

        //
        // Method body
        //
        for (int i = 0; i < 5; i++) {
            for (int j = 0; j < 5; j++) {
                System.out.print(i * j + " ");
            }
            System.out.println("");
        }

        if (logger.isLoggable(Level.INFO)) {
            logger.info("Exiting executeMethod() at  : " + new Date());
        }
    }
}

The result of our example code above is shown below:

28 Apr 09 6:08:55 org.kodejava.example.util.logging.ConditionalLogging executeMethod
INFO: Entering executeMethod() at : Tue Apr 28 06:08:55 SGT 2009
0 0 0 0 0 
0 1 2 3 4 
0 2 4 6 8 
0 3 6 9 12 
0 4 8 12 16 
28 Apr 09 6:08:55 org.kodejava.example.util.logging.ConditionalLogging executeMethod
INFO: Exiting executeMethod() at  : Tue Apr 28 06:08:55 SGT 2009

Wayan Saryada

Programmer, runner, recreational diver, currently living in the island of Bali, Indonesia. Mostly programming in Java, creating web based application with Spring Framework, Hibernate / JPA.

Leave a Reply