logging

Check if message is loggable

This is an example of how to check if a message is loggable. We are going to use a Logger with logging.Level set to WARNING and then log messages in different levels, in order to check if they are loggable. To do so, we have to:

  • Create an instance of Logger, with the getLogger(String name) API method, using as parameter the name of Class that uses the Logger.
  • Set the logging level to Level.WARNING, with the setLevel(Level newLevel) API method of the Logger. In this case logging at WARNING and all higher levels is enabled.
  • Use the isLoggable(Level level) API method of the Logger for different levels, such as INFO, WARNING, SEVERE, and use the corresponding methods of the logger, info(String msg), warning(String msg), severe(String msg) to log a message in different levels. Since the level is set to WARNING in this example, only the messages that are logged to WARNING and above will be logged.

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;
 
public class LoggingLevelCheckExample {
	
    public static void main(String[] args) {

  
    	// Create an instance of Logger and set the logging level to Level.WARNING.

  Logger log = Logger.getLogger(LoggingLevelCheckExample.class.getName());

  log.setLevel(Level.WARNING);
 

  // Log INFO level message

  if (log.isLoggable(Level.INFO)) {


log.info("Application Info Message");

  }
 

  // Log WARNING level message when Level.WARNING is loggable.

  if (log.isLoggable(Level.WARNING)) {


log.warning("Application Warning Information");

  }
 

  // Log SEVERE level message when Level.SEVERE is loggable.

  if (log.isLoggable(Level.SEVERE)) {


log.severe("Info Severe Information");
     

  }
    }
}

Output:

Αυγ 12, 2012 2:01:54 ΜΜ com.javacodegeeks.snippets.core.LoggingLevelCheckExample main
WARNING: Application Warning Information
Αυγ 12, 2012 2:01:54 ΜΜ com.javacodegeeks.snippets.core.LoggingLevelCheckExample main
SEVERE: Info Severe Information

 
This was an example of how to check if a message is loggable in Java.

Byron Kiourtzoglou

Byron is a master software engineer working in the IT and Telecom domains. He is an applications developer in a wide variety of applications/services. He is currently acting as the team leader and technical architect for a proprietary service creation and integration platform for both the IT and Telecom industries in addition to a in-house big data real-time analytics solution. He is always fascinated by SOA, middleware services and mobile development. Byron 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