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 message 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.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 increase the level
    // to Level.WARNING or Level.SEVERE so that these message will not
    // be 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:

Oct 07, 2021 8:26:49 PM org.kodejava.util.logging.ConditionalLogging executeMethod
INFO: Entering executeMethod() at : Thu Oct 07 20:26:49 CST 2021
Oct 07, 2021 8:26:49 PM org.kodejava.util.logging.ConditionalLogging executeMethod
INFO: Exiting executeMethod() at  : Thu Oct 07 20:26:49 CST 2021
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 
Wayan

Leave a Reply

This site uses Akismet to reduce spam. Learn how your comment data is processed.