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.

Want to know how to develop your skillset to become a Java Rockstar?

Join our newsletter to start rocking!

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

I have read and agree to the terms & conditions

 

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
8 months ago

why the log message is printed twice ?

Back to top button