Introduction to Java Logging

Java Logging

Java logging is a remarkable feature to trace errors and track your code. Find out more about how Java logging works and how you can use it in your application.


Java logging is one of the important debugging tools for developers. It is a powerful feature that helps developers understand the run-time behavior of programs and trace out the errors. Java has been offering this logging approach for a while now. The Logging API used in Java was initially introduced in Java 1.4 version. It provides the ability to automatically capture and log the data. These logs contain some very important data that is also available for analysis at any stage of development.

In this article, we will explore how Java Logging works and how you can take advantage of it in the debugging process. We will also cover the Java logger API and its components along with some popular Java logging frameworks available such as Log4j 2 and Logback.

See Also: Java Developer Job Description: What Is A Java Developer And How To Become One

Java Logging API

The most common approach for logging in Java is the Logging API. It provides the options to trace out the occurring errors in Java applications. First, a logging call is generated by the application when an error occurs, the Logger then records the event in the LogRecord. It is then sent to its respective appenders or handlers. Lastly, the log records are formatted using the formatter to send them to the console or to be saved in the log file.

Logging is not only used to record the critical failure if any occur in an application but it also collects the complete tracing information of the application that can be very helpful in terms of reusability or to make the application more efficient.

See Also: Does python have an equivalent to Java Class.forName()?

Elements of Java Logging API

As mentioned earlier, Java logging API can be broken down into some stages. These stages are equipped with different elements that are used by the developers to create the logs and format them in a certain layout.

The following are the three main elements in Java logging API:

1. Logger (logger objects)

The application code written by the developers sends the log requests to the Logger objects. These logger objects determine if a log request is to be processed by checking it by a certain log level. The log requests below a certain level are rejected. After capturing the log records, they are passed to the corresponding appender.

Usually, the Loggers objects are named entities that are separated by the dot operator. The namespace is managed by the LogManager and it is represented in hierarchical order. A logger can also inherit certain attributes from their parent like Logging Levels, Handlers and Resource bundle names. If any of these values are null, it is then traversed back to the parents to search for the first non-null value.

2. Logging Handler

Java Logging API allows the use of multiple handlers in a Java logger. The appenders process the logs accordingly to the requirements.

There are five logging handlers in Java:

  • FileHandler writes the log message either to a single XML log file or multiple rotating log files. It is the most commonly used handler as logs are usually captured in a file(s). It is also one of two handlers that are provided by default in Java logging API.
  • ConsoleHandler writes all the formatted log messages to the console to be printed on the screen. It is also provided by default.
  • StreamHandler writes the formatted log message to an OutputStream.
  • SocketHandler is used to write the log message to the remote TCP ports.
  • MemoryHandler handles the buffer log records residing in the memory.

Using Custom Handler

Java logging API also allows developers to create their own subclass or they can also customize the Handler class by extending the Handler class or any of the handler subclasses as per the logging requirements.

See this code snippet below demonstrating the extension of SteamHandler:

1.   import java.util.logging.LogRecord;  
2.   import java.util.logging.StreamHandler;  
3.   public class DemoHandler extends StreamHandler   
4.   {  
5.     @Override  
6.     public void publish(LogRecord rec)   
7.     {  
8.       //You can add your own logic here to customize the streamHandler subclass
9.       super.publish(rec);  
10.    }  
11.   @Override  
12.   public void flush()   
13.   {  
14.     super.flush();  
15.   }  
16.   @Override  
17.   public void close() throws SecurityException   
18.   {  
19.     super.close();  
20.   }  
21. }  

3. Logging Formatters

The logging formatters are used to format the logs and convert them into log events. The SimpleFormatter and XML formatter are two standard formatters classes provided by Java by default.

· Simple Formatter

The simple Formatter class generates a text message containing the general information from the logs. It creates the human-readable summaries of the log messages. The ConsoleHandler subclass is then used along to print the log message on the screen. For instance, see the following console message to be printed on the screen

Jun 28, 2022 12:16:38 PM DemoClass main  

SEVERE: An exception occurred.  

· XML Formatter

The XML Formatter is the default formatter for FileHandler. It generates the log message in XML format, producing an XML structure to present information.

See the following log entry in XML code:

1.   <?xml version="1.0" encoding="UTF-8" standalone="no"?>  
2.   <!DOCTYPE log SYSTEM "logger.dtd">  
3.   <log>  
4.   <record>  
5.   <date>2022-06-29T13:29:15</date>  
6.   <millis>1406931298</millis>  
7.   <sequence>0</sequence>  
8.   <logger>myClass</logger>  
9.   <level>SEVERE</level>  
10. <class>myClass</class>  
11. <method>main</method>  
12. <thread>1</thread>  
13. <message>An exception has occurred.</message>  
14. </record>  
15. </log>  

Using Custom Formats

Similar to the Handler class, the Formatter class can also be customized or you can create your own Formatter class by extending the formatter class. It can still be used with the customized class with any handlers.

See this code snippet demonstrating a Customized Formatter Class.

1.   import java.util.Date;  
2.   import java.util.logging.Formatter;  
3.   import java.util.logging.LogRecord;  
4.   public class DemoFormatter extends Formatter   
5.   {  
6.   @Override  
7.   public String demoFormat(LogRecord rec)   
8.   {  
9.   return rec.getThreadID()+"||"+rec.getSourceClassName()+"||"+rec.getSourceMethodName()+"||"+rec.getMessage()+"\n";  
10. }  
11. } 

Certain tweaks can be done by extending the classes to customize the formatter as per your needs but If you do not want to go with Simple formatter or XML formatter, there are some advanced formats available that allow using other layouts such as HTML, plain text or JSON but it would require to use a separate Java logging framework.

Java logging frameworks

The Java logging frameworks can be some good options for Java logging other than Java logging API. There are some excellent Java logger frameworks available if you are looking for some extra features or want to use an advanced layout other than the ones offered by JavaSE by default.

1. Log4j version 2

Log4j version 2 or Log4j2 is the predecessor of the popular Log4j logging framework by Apache since it was discontinued in 2015. This new version comes with some great improvements one of which is the possibility of asynchronous logging.

Log4j2 requires the following dependencies to work:

1.   <dependency>
2.   <groupId>org.apache.logging.log4j</groupId>
3.   <artifactId>log4j-api</artifactId>
4.   <version>2.6.1</version>
5.   </dependency>
6.   <dependency>
7.   <groupId>org.apache.logging.log4j</groupId>
8.   <artifactId>log4j-core</artifactId>
9.   <version>2.6.1</version>
10. </dependency>

The following code example demonstrates the use of Log4j2 for logging an application:

1.   import org.apache.logging.log4j.Logger;
2.   import org.apache.logging.log4j.LogManager;
3.   public class DemoLog4j2 {
4.      private static Logger myLogger = LogManager.getLogger(DemoLog4j2.class);
5.      public static void main(String[] args) {
6."message for Info log");        
7.        myLogger.debug("message for Debug log");
8.        myLogger.error("message for Error log");
9.       }
10.  }

You can also use the logger.error Method to log an exception:

1.   try {
2.   // exception
3.   } catch (Exception e) {
4.   myLogger.error("log message Error", throwable);
5.   }

After execution, the following messages will be logged into the log file and will also be displayed on the console:

2022-06-10 13:17:23 INFO Info log message

2022-06-10 13:17:23 ERROR Error log message

2. Logback

Logback is meant to be an improved version of Log4j, developed by Apache, the same developers who are behind Log4j. It is an open-source framework released right after Log4j but before the release of Log4j2. Logback offers a lot more features as compared to Log4j. Its way faster implementation, extensive documentation and shifting appenders are to name a few.

To work with logback, you will need to add the following dependency to the pom.xml file:






3. SLF4J (The Simple Logging Facade for Java)

Unlike log4j and logback, SLF4J is not a Java logging framework. It has still made into the list because it is an abstraction that serves as a facade and provides a standardized API that enables the developers to work with any of the logging frameworks of their choice. Logback uses SLF4J as a native API for its functionality.

See the following import statements needed to be used for Logback logging:

import org.slf4j.Logger;

import org.slf4j.LoggerFactory;


This article explores the workings of Java logging. We discussed the working of the Java logging API and how all of its components work. We also looked into some examples of how you can use different logging frameworks like Log4j2 and Logback. Java logging is no doubt a great feature to identify the errors or exceptions in your code saving you a lot of time and resources in debugging process.

See Also: Smarter Application Logging: Java Logging 101

Most Popular

To Top
India and Pakistan’s steroid-soaked rhetoric over Kashmir will come back to haunt them both clenbuterol australia bossier man pleads guilty for leadership role in anabolic steriod distribution conspiracy