logging

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:

  • Create a Class and create a new logger instance for the Class.
  • Create a new instance of the class and invoke its method. The method has a simple functionality.
  • In the beggining and at the end of the method check if the logger level is set to INFO. If so, use the info(String msg) API method to log a message.

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.

Ilias Tsagklis

Ilias is a software developer turned online entrepreneur. He is co-founder and Executive Editor at Java Code Geeks.
Subscribe
Notify of
guest

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

0 Comments
Oldest
Newest Most Voted
Inline Feedbacks
View all comments
Back to top button