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 thesetLevel(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 asINFO
,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:
01 02 03 04 05 06 07 08 09 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 | 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.