Conditional logging

This is an example of how to use Conditional logging. Using conditional logging in a Class means that we check the Level for which the Logger is enabled before we log a message to that level. We have implemented a Class that uses a logger. The Class consists of a simple method that uses the logger to log messages after checking the logging level. The basic steps of the example are:

Let’s take a look at the code snippet that follows:

package com.javacodegeeks.snippets.core;
import java.util.logging.Logger;
import java.util.logging.Level;
import java.util.Date;
 
public class ConditionalLoggingExample {
	
    private Logger logger = Logger.getLogger(ConditionalLoggingExample.class.getName());
 
    public static void main(String[] args) {
    	
  ConditionalLoggingExample example = new ConditionalLoggingExample();
  example.Method();
    }
 
 
    public void Method() {
  // Check if the logging level before enter into the log
  if (logger.isLoggable(Level.INFO)) {
logger.info("Entering executeMethod() at : " + new Date());
  }
 
  // Method functionality
  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());
  }
    }
}

Output:

Αυγ 12, 2012 1:45:55 ΜΜ com.javacodegeeks.snippets.core.ConditionalLoggingExample Method
INFO: Entering executeMethod() at : Sun Aug 12 13:45:55 EEST 2012
0 1 2 3 4 
1 2 3 4 5 
2 3 4 5 6 
3 4 5 6 7 
4 5 6 7 8 
Αυγ 12, 2012 1:45:55 ΜΜ com.javacodegeeks.snippets.core.ConditionalLoggingExample Method
INFO: Exiting executeMethod() at  : Sun Aug 12 13:45:55 EEST 2012

 
This was an example of how to use Conditional logging in Java.

Exit mobile version