Programming Examples

Are you a Programmer or Application Developer or a DBA? Take a cup of coffee, sit back and spend few minutes here :)

Java Logging Using LogManager and Logger

1. Introduction to Application Logging

Before we dig into Java LogManager and Logger, we will see why logging is required. A Java program or component running in the production system may malfunction at specific conditions. This is a program bug. When this case rises, source code debugging as we do it in the development machine is not feasible. Because the installer will not deploy the debugging symbols and source code in the target machine. Debugging Symbols are extra data packed with the binary output of a program. They will help in debugging the errors as we can map it to the source code.

The software engineers use Logging to catch the application actions from the target system. Logging avoids deploying the Debugging Symbols and source code in the production machine. Have a look at the below depiction:

Capturing Log at Production System

Capturing Log at Production System

The logging goes as a binary component in the application itself. In most cases, the configuration file takes care of turning ON or OFF the logging. When wrongdoing of the application or crash happens, the production site will turn ON the Logging to produce the “Log File”. The Log file taken in the production will be shipped to the software support engineers for further research to know what went on the production system.

Log Files are mostly an AscII format readable files which has application activities captured in it.

In the above model, in place of deploying the debug information along with binary, the logging system is deployed as a component to grab the application information. In this example, we will see how to produce Log information using java.util.logging package. Here, we will not create any log file. But, we will display the Log Message in the console window.

2. The LogManager Object

A Java Application can hold only one LogManager  object. This single Java LogManager object maintains multiple Loggers, Handlers, etc. This means, once we have LogManager in hand, we can claim other objects needed for the logging.

The LogManager Class has a static method called getLogManager(). This method sets up the LogManager object and returns that to the caller. It is not possible to change LogManager object after it is claimed.

3. The Logger and Log Level

The getLogger() method of the LogManager class returns the Logger object to its caller. While getting the Logger, we can give a name to it by sending a string as an argument to the getLogger() call. The naming follows a hierarchical notation which allows the parent-child relation between Loggers. This is useful when the system has multiple Loggers.

A Java program running in the production uses the Logger to catch the run-time conditions. Logging output can be delivered to a special receiver like Network Socket, Files or Console Window etc. Java uses Handler  object to do this.

Each logging call to the Logger goes with a Logging Level which aids message filtering. For Example, let us tell the Log Levels are 1,2,3,4 where 1 is a high level (Critical) message and 4 is a low-level message (developer debug information). Let us further say, the LogLevel in the Logger is 1. Now, the logger will pump only the Critical Message to the Log Receiver (File, Console etc). It rejects all other log request with a log level higher than 1.

In this example, we will see how we log a message. We will deal with the Logging Level in a distinct Example.

4. Logging – A Simple Example

Listing 1: Package inclusion for Logging

To perform logging, we require Logger from the package java.util.logging. To use Logger, we need to have the LogManager. The below import statements imports the required Java API classes to our example.

//Snippet 01: Package inclusion
import java.util.logging.LogManager;
import java.util.logging.Logger;
import java.util.logging.Level;

Listing 2: Get Java LogManager Instance

First, we get the application wide LogManager object and store that in a reference called lgMan. The static method getLogManager() gives us the Java LogManager instance. Below is the code:

//Snippet 02: Get the Log Manager Instance
LogManager lgMan = LogManager.getLogManager();

Listing 3: Get Logger From LogManager And Set Log Level

After getting the LogManager, we are setting a name for our Logger using the GLOBAL_LOGGER_NAME constant from the Logger class. We are passing this global constant to the getLogger() method of the LogManager instance. This call will give us the Logger instance with a name assigned by Java. Note, it is also possible to pass our own name to the getLogger method. For this basic example, we used the name assigned by the system.

Now, the Logger is ready for logging the application specific information. Before we go for actual logging, we are setting the Log Level to the logger by calling the setLevel() method. The Level.ALL constant tells the logger not to filter any message. This means, we are asking to log all the messages to the target (Console, Flat file etc). Below is the code:

//Snippet 03: Get Logger from Log Manager
String LoggerName = Logger.GLOBAL_LOGGER_NAME;
Logger Logr = lgMan.getLogger(LoggerName);
Logr.setLevel(Level.ALL);

Listing 4: Logging The Messages

The log() method of the Logger class performs the logging. In the below code fragment, we are logging two informational messages. This is done by sending a constant Level.INFO as the first parameter. The second parameter is a string containing the actual message which we want to log.

Since we set Logger with the Level.ALL Logging Level, the logger will log any message sent to it. This is a Console Application, and the logged messages go to Console Output Window once log() method is called. Below is the code:

//Snippet 04: Perform the Logging
Logr.log(Level.INFO, "First Log Entry");
Logr.log(Level.INFO, "Second Log Entry");

That is all. If you compile and run, you can see the logged messages in the console output window. You can read more about logging from the below article links.

  1. Owlcation Article: Logging Level Explained
  2. Owlcation Article: Perform Logging using Different Log Handlers

5. Full Code Example of Java LogManager and Logging

//Snippet 01: Package inclusion
import java.util.logging.LogManager;
import java.util.logging.Logger;
import java.util.logging.Level;
 
public class Main
{
    public static void main(String[] args)
    {
        //Snippet 02: Get the Log Manager Instance
        LogManager lgMan = LogManager.getLogManager();
 
        //Snippet 03: Get Logger from Log Manager
        String LoggerName = Logger.GLOBAL_LOGGER_NAME;
        Logger Logr = lgMan.getLogger(LoggerName);
        Logr.setLevel(Level.ALL);
 
        //Snippet 04: Perform the Logging
        Logr.log(Level.INFO, "First Log Entry");
        Logr.log(Level.INFO, "Second Log Entry");
    }
}

Code output

Output of Java LogManager Example

Output of Java LogManager Example

About the Program Output

Note that in the output we also get the Date and Time of the logged messages. The purpose of Logging is to diagnose the behavior of the application at a specific time. This is the reason the logger is appending the Date & Time for every logged message. The below picture shows the date and time with a yellow line. The actual message is in blue line.

Categories: Java

Tags: , ,

Do you like this Example? Share your thoughts!!

This site uses Akismet to reduce spam. Learn how your comment data is processed.