logging
Set logger log level
With this example we are going to demonstrate how to set a Logger‘s log level. The Level defines a set of standard logging levels that can be used to control logging output. The standard levels are provided at the Level API. In short, to set logger log level you should:
- Create a new Logger instance.
- Set the log level to
Level.INFO
, with thesetLevel(Level newLevel)
API method. - Log a
SEVERE
message, with thesevere(String msg)
API method. The message will be logged, since the level is set toINFO
. - Set the log level to
Level.SEVERE
, with thesetLevel(Level newLevel)
API method. - Log a
WARNING
message, with thewarning(String msg)
API method. The message will not be logged, since the level is set toSEVERE
. - Set the log level to
Level.OFF
, with thesetLevel(Level newLevel
) API method, to turn the logger off. Now no messages will be logged. - Set the log level to
Level.ALL
, with thesetLevel(Level newLevel)
API method, to turn the logger on. Now all messages 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 LogLevelExample { // Create logger instance private static Logger logger = Logger.getLogger(LogLevelExample.class.getName()); public static void main(String[] args) { // Set the log level to Level.INFO logger.setLevel(Level.INFO); logger.severe("This message will be logged."); // Set the log level to Level.SEVERE logger.setLevel(Level.SEVERE); logger.warning("This message won't be logged."); // Turn of the log logger.setLevel(Level.OFF); logger.info("All log is turned off."); // Turn the logger on logger.setLevel(Level.ALL); logger.info("Information message."); logger.warning("Warning message."); logger.severe("Severe message."); } }
Output:
Αυγ 12, 2012 1:03:32 ΜΜ com.javacodegeeks.snippets.core.LogLevelExample main
SEVERE: This message will be logged.
Αυγ 12, 2012 1:03:32 ΜΜ com.javacodegeeks.snippets.core.LogLevelExample main
INFO: Information message.
Αυγ 12, 2012 1:03:32 ΜΜ com.javacodegeeks.snippets.core.LogLevelExample main
WARNING: Warning message.
Αυγ 12, 2012 1:03:32 ΜΜ com.javacodegeeks.snippets.core.LogLevelExample main
SEVERE: Severe message
This was an example of how to set a logger’s log Level in Java.