logging

Use of logger console handler

In this example we shall show you how to use a logger’s ConsoleHandler. The ConsoleHandler is a handler that takes logs from a Logger and publishes them to System.err. To use the ConsoleHandler one should perform the following steps:

  • Create a Logger instance, with the getLogger(String name) API method of the Logger.
  • Create a ConsoleHandler for System.err.
  • Add the handler to the logger so as to receive messages from the logger, with the addHandler(Handler handler) API method.
  • Check if the logger is enabled to a specific level and then log a message to that level, with the isLoggable(Level level) and info(String msg) API methods,

as described in the code snippet below.

package com.javacodegeeks.snippets.core;

import java.util.logging.Logger;
import java.util.logging.ConsoleHandler;
import java.util.logging.Level;
 
public class LogConsoleHandler {
   
	public static void main(String[] args) {
   

  // Create Logger instance

  Logger logger = Logger.getLogger(LogConsoleHandler.class.getName());
 

  // Add ConsoleHandler

  ConsoleHandler consoleHandler = new ConsoleHandler();

  logger.addHandler(consoleHandler);
 

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


logger.info("This is information message");

  }
    }
}

Output:

Αυγ 12, 2012 1:06:36 ΜΜ com.javacodegeeks.snippets.core.LogConsoleHandler main
INFO: This is information message
Αυγ 12, 2012 1:06:36 ΜΜ com.javacodegeeks.snippets.core.LogConsoleHandler main
INFO: This is information message

 
This was an example of how to use logger ConsoleHandler 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.

1 Comment
Oldest
Newest Most Voted
Inline Feedbacks
View all comments
Hariharan P
Hariharan P
1 year ago

why the log message is printed twice ?

Back to top button