Home » Core Java » util » logging » Conditional logging

About Ilias Tsagklis

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

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.

(No Ratings Yet)
Start the discussion Views Tweet it!

Do you want to know how to develop your skillset to become a Java Rockstar?

Subscribe to our newsletter to start Rocking right now!

To get you started we give you our best selling eBooks for FREE!

 

1. JPA Mini Book

2. JVM Troubleshooting Guide

3. JUnit Tutorial for Unit Testing

4. Java Annotations Tutorial

5. Java Interview Questions

6. Spring Interview Questions

7. Android UI Design

 

and many more ....

 

Receive Java & Developer job alerts in your Area

 

Leave a Reply

avatar
  Subscribe  
Notify of