Logging Messages using Java Logging API

The Logging API in Java enables Applications to log messages of some level which will be very useful for debugging purpose. Say, if a system fails for some reasons, then the reason can be easily traced out by looking at the information available in the log file. In this section, let us see an overview of using Logging facility in Java.

Starting from 1.4.2, Java provides the capability for Applications to log messages through the package java.util.logging and the core class in the API is the Logger class. It is important to understand the various levels that are available in logging messages. Java defines eight levels of logging messages and they are SEVERE, WARNING, INFO, CONFIG, FINE, FINER, FINEST and ALL. The eight levels are given in the descending order of higher priority. At any point of time within the Application, the level of logging can be changed. In general, when a level is specified to a Logger, the Logger will include the current specified level as well as all the levels in the upper part of the level hierarchy. For example, if the level is set to WARNING, all the warning messages as well as the SEVERE Messages will be logged. Applications can log messages by using methods like Logger.warning(), Logger.info(), Logger.config() etc. Consider the following code followed by explanation,

The above LoggingClass logs various messages of different levels by calling Logger.severe(), Logger.warning() and Logger.info() methods. Now let us look into the following Client Application that makes use of the above class.

The above class instantiates a named Logger object by calling the Logger.getLogger() method. Then it sets the level of the messages to be logged. Since the level is set to Level.INFO, all the level of messages upward the INFO hierarchy, i.e WARNING and SEVERE, including INFO will be logged. The following is the output of the above program,

We find that the date/time information along with the method name is logged to the console. However, it is possible to send all the messages to a file rather than the console by calling the following method,

logger.addHandler(new FileHandler('log.txt'));

Handlers are nothing but the destination point for log messages. It is possible to add multiple Handlers to a Logger instance. Other variations of Handler include MemoryHandler, SocketHandler, ConsoleHandler etc. By default, the format of messages that are logged are in simple text format and it is also possible to log the messages in XML Format as the following code just do that,

About Krishna Srinivasan

He is Founder and Chief Editor of JavaBeat. He has more than 8+ years of experience on developing Web applications. He writes about Spring, DOJO, JSF, Hibernate and many other emerging technologies in this blog.