Java logging simple example

This post explains java logging with simple example.

Main code


1  package Logging;
2  
3  import java.io.IOException;
4  import java.util.logging.Logger;
5  
6  public class LoggingDemo1 {
7   public static void main(String[] args) throws IOException {
8       Logger logger = Logger.getLogger("logger1");
9       logger.info("Hello my name is Mathew");
10      logger.warning("Hello my name is Mathew");
11      logger.config("Hello my name is Mathew");
12  }
13 }

Explanation

To log messages we need a Logger object which we obtain by calling static method “getLogger” on Logger class. Refer to line 8.

Each logger object can be identified by giving them a name which we do by passing the name as the argument to getLogger method.

The getLogger method checks if a logger identified by given name already exists. If yes returns that object otherwise create a new logger object
associate the object with the name for future reference.

Once we obtain the logger object we can log messages as shown at line 9.

Each message is logged at a particular level, in this case it is INFO. The java logging framework provides the below levels sorted with their severity in descending order
SEVERE (highest value)
WARNING
INFO
CONFIG
FINE
FINER
FINEST (lowest value)

Each logger object has reference to Handler object, to which it sents the messages and its the Handler object responsible for logging the message.

In this case, out of the box, when the logger object is created, it is assigned an instance of ConsoleHandler which prints messages to console.

Out of the box, ConsoleHandler only accepts messages at or above INFO level.

Only messages with level at or above the level assigned to logger and handler object are allowed to be logged.

In case of our example, only messages at WARNING and INFO level are logged. Message at CONFIG level was ignored.

Output

Jun 24, 2017 7:46:16 AM Logging.LoggingDemo1 main
INFO: Hello my name is Mathew
Jun 24, 2017 7:46:16 AM Logging.LoggingDemo1 main
WARNING: Hello my name is Mathew

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s