Thursday, January 8, 2015

Explaining Logging with java.util.Logging System

Logging is a kind of a recording mechanism of the activities occurred during the execution of a program. Further it can store exception and warnings as well as information which are mentioned as to log.

java.util.logging system facilitates logging functions. Logger is the java object used to log a message. Logger creates LogRecord object to store the relevant information to be logged and this object is passed to the handlers to be used for relevant formatting and printing.

Handler objects are assigned to the Logger. These are responsible for publishing the log messages to the external systems. The associated Filter objects do the relevant filtering.


When creating Loggers it is recommended to provide a name based on the package and the class name in which the logger is created.

import java.io.IOException;
import java.util.logging.Logger;

public class LoggerExample {

 private static final Logger LOGGER = Logger.getLogger(LoggerExample.class.getName());

 // Code goes here..........
}

Handler is responsible for publishing the log message at the target destination. It can be a file or the Standard output.

StreamHandler : Publishes all the log messages to an OutputStream
FileHandler : Records all the log messages to a specific file
SocketHandler : Publishes all the log messages to a network stream connection.
MemoryHandler : Keeps the log messages in a memory buffer

We can configure the handlers, formatters, filters and levels through the methods provided for the Logger class.

Also we can configure those using a properties file inside which the relevant configuration information are defined.

Here is a simple configuration file.

handlers=java.util.logging.ConsoleHandler.level=ALL
java.util.logging.ConsoleHandler.level=ALL
java.util.logging.ConsoleHandler.formatter=java.util.logging.SimpleFormatter
confLogger.level=ALL

Using the above configuration file here is how to configure the logger.

import java.io.FileInputStream;
import java.io.IOException;
import java.util.logging.Level;
import java.util.logging.LogManager;
import java.util.logging.Logger;

public class LoggerConfigurationExample {

     private static final LogManager logManager = LogManager.getLogManager();
     private static final Logger LOGGER = Logger.getLogger(LoggerConfigurationExample.class.getName());

     static{
           try {
                      logManager.readConfiguration(new FileInputStream("./logger.properties"));
           } catch (IOException exception) {
                      LOGGER.log(Level.SEVERE, "Error in loading configuration file",exception);
           }
     } 

     public static void main(String[] args) {
           LOGGER.fine("Test logging configuration");
     }
}

Happy coding.....:)

No comments: