Log4j

Log4j Conversion Pattern Example

Logging is a critical feature of any application. In this tutorial, I will show you how to implement some useful Log4j Conversion Patterns for writing the logging mechanism in Java development.

1. Introduction

Printing messages to the console is an integral part of the development testing and the debugging of a Java program. If developers are working on a Server side application, where they cannot see what’s going on inside the server, then their only visibility tool is a log file.

Without logs, developers cannot do any debugging or see what’s going on inside the application. Java has pretty handy System.out.println() methods to print something on the console, which can also be routed to a log file but it is not sufficient for a real-world Java application.

If developers are running a Java program in Linux or Unix based systems, Log4j or SLF4j or any other logging framework offers a lot more features, flexibility, and improvement on message quality, which is not possible using the System.out.println() statements.

1.1 What is Log4j?

Log4j is a simple, flexible, and fast Java-based logging framework. It is thread-safe and supports internationalization. We mainly have 3 components to work with Log4j:

  • Logger: It is used to log the messages
  • Appender: It is used to publish the logging information to the destination like file, database, console etc
  • Layout: It is used to format logging information in different styles

1.2 Log4j Conversion Pattern

To recall, a Log4j Conversion Pattern specifies that the log messages are formatted by using a combination of literals, conversion characters, and the format modifiers. Consider the following pattern:

log4j.appender.ConsoleAppender.layout.ConversionPattern=[%-5p] %d %c - %m%n

Where:

  • The percentage sign (%) is a prefix for any conversion characters
  • -5p is the format modifier for the conversion character p (i.e. priority). This justifies the priority name with a minimum of 5 characters

The above conversion pattern will format the log messages to something like this:

[DEBUG] 2017-11-14 21:57:53,661 DemoClass - This is a debug log message.
[INFO ] 2017-11-14 21:57:53,662 DemoClass - This is an information log message.
[WARN ] 2017-11-14 21:57:53,662 DemoClass - This is a warning log message.

The following table briefly summarizes the conversion characters defined by the Log4j framework:

What to printConversion characterPerformance
Category Name (or Logger Name)cFast
Fully Qualified Class NameCSlow
Date and Timed
d{format}
Slow if using JDK’s Formatters.
Fast if using Log4j Formatters.
Filename of Java classFExtremely slow
Location (Class, Method, and line number)lExtremely slow
Line Number onlyLExtremely slow
Log MessagemFast
Method NameMExtremely slow
Priority (level)pFast
New Line SeparatornFast
Thread NametFast
Time Elapsed (in milliseconds)rFast
Thread’s Nested Diagnostic ContextxFast
Thread’s Mapped Diagnostic ContextXFast
Percent Sign%%Fast

1.3 Why prefer Log4j over System.out.println?

Below are some of the reasons, which are enough to understand the limitation of using System.out.println(),

  • Any logging framework including allows developers to log debugging information to a log level which can be used as filtering criteria, i.e. one can disable the message belongs to a particular log level. For e.g., Developers would be more concerned to see the WARN messages than the DEBUG messages in the production environment
  • Logging framework can produce better outputs and metadata which helps to troubleshoot and debug. For e.g., Log4j allows to print formatted output by specifying a formatting pattern i.e. by using PatternLayout one can include a timestamp, class name etc

Now, open up the Eclipse Ide and let’s start building the application!

2. Log4j Conversion Pattern Example

Below are the steps involved in developing this application.

2.1 Tools Used

We are using Eclipse Kepler SR2, JDK 8, and Log4j Jar. Having said that, we have tested the code against JDK 1.7 and it works well.

2.2 Project Structure

Firstly, let’s review the final project structure, in case you are confused about where you should create the corresponding files or folder later!

Fig. 1: Log4j Conversion Pattern Application Project Structure
Fig. 1: Application Project Structure

2.3 Project Creation

This section will demonstrate on how to create a Java-based Maven project with Eclipse. In Eclipse Ide, go to File -> New -> Maven Project.

Fig. 2: Create Maven Project
Fig. 2: Create Maven Project

In the New Maven Project window, it will ask you to select a project location. By default, ‘Use default workspace location’ will be selected. Select the ‘Create a simple project (skip archetype selection)’ checkbox and just click on next button to proceed.

Fig. 3: Project Details
Fig. 3: Project Details

It will ask you to ‘Enter the group and the artifact id for the project‘. We will input the details as shown in the below image. The version number will be by default: 0.0.1-SNAPSHOT.

Fig. 4: Archetype Parameters
Fig. 4: Archetype Parameters

Click on finish and the creation of a maven project will be completed. If you observe, it has downloaded the maven dependencies and a pom.xml file will be created. It will have the following code:

pom.xml

<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
	<modelVersion>4.0.0</modelVersion>
	<groupId>Log4jConversionPattern</groupId>
	<artifactId>Log4jConversionPattern</artifactId>
	<version>0.0.1-SNAPSHOT</version>
</project>

We can start adding the dependencies that developers want like Log4j, Junit etc. Let’s start building the application!

3. Application Building

Below are the steps involved in developing this application.

3.1 Maven Dependencies

In this example, we are using the most stable Log4j version in order to set-up the logging framework. The updated file will have the following code:

pom.xml

<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
	xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
	<modelVersion>4.0.0</modelVersion>
	<groupId>Log4jConversionPattern</groupId>
	<artifactId>Log4jConversionPattern</artifactId>
	<version>0.0.1-SNAPSHOT</version>
	<packaging>jar</packaging>
	<dependencies>
		<!-- https://mvnrepository.com/artifact/log4j/log4j -->
		<dependency>
			<groupId>log4j</groupId>
			<artifactId>log4j</artifactId>
			<version>1.2.17</version>
		</dependency>
	</dependencies>
</project>

3.2 Java Class Creation

Let’s create the required Java files. Right-click on src/main/java folder, New -> Package.

Fig. 5: Java Package Creation
Fig. 5: Java Package Creation

A new pop window will open where we will enter the package name as: com.jcg.log4j.

Fig. 6: Java Package Name (com.jcg.log4j)
Fig. 6: Java Package Name (com.jcg.log4j)

Once the package is created, we will need to create the implementation class. Right-click on the newly created package, New -> Class.

Fig. 7: Java Class Creation
Fig. 7: Java Class Creation

A new pop window will open and enter the file name as: Log4jPattern. The implementation class will be created inside the package: com.jcg.log4j.

Fig. 8: Java Class (Log4jPattern.java)
Fig. 8: Java Class (Log4jPattern.java)

3.2.1 Implementation of Utility Class

Let’s write a quick Java program containing a simple priority, category, method-name, and message pattern and write the log message to the console.

Log4j Simple Conversion Pattern

[%p] %c %M - %m%n

Where:

  • %n should be used to add a new line character at the end of every message

Add the following code to it.

Log4jPattern.java

package com.jcg.log4j;

import org.apache.log4j.Logger;

public class Log4jPattern {

	static Logger logger = Logger.getLogger(Log4jPattern.class);

	public static void main(String[] args) {

		logger.info("This Is A Log Message ..!");
	}
}

3.3 Log4j Configuration File

Log4j will be usually configured using a properties file or an XML file. So once the log statements are in place developers can easily control them using the external configuration file without modifying the source code. The log4j.xml file is a Log4j configuration file which keeps properties in key-value pairs. By default, the LogManager looks for a file named log4j.xml in the CLASSPATH.

To configure the logging framework, we need to implement a configuration file i.e. log4j.xml and put it into the src/main/resources folder. Add the following code to it:

log4j.xml

<?xml version="1.0" encoding="UTF-8"?>
<log4j:configuration debug="true" xmlns:log4j="http://jakarta.apache.org/log4j/">
    <appender name="console" class="org.apache.log4j.ConsoleAppender">
        <layout class="org.apache.log4j.PatternLayout">
            <param name="ConversionPattern" value="[%p] %d [%t] %x %c %M - %m%n" />
        </layout>
    </appender>
    <root>
        <level value="INFO" />
        <appender-ref ref="console" />
    </root>
</log4j:configuration>

4. Run the Application

To run the application, Right click on the Log4jPattern class, Run As -> Java Application. Developers can debug the example and see what happens after every step. Enjoy!

Fig. 9: Run Application
Fig. 9: Run Application

5. Project Demo

The code shows the following status as output.

  • Simple Conversion Pattern: [%p] %c %M - %m%n
    Output

    [INFO] com.jcg.log4j.Log4jPattern main - This Is A Log Message ..!
  • Standard Conversion Pattern: [%p] %d %c %M - %m%n
    Output

    [INFO] 2017-11-14 20:30:20,434 com.jcg.log4j.Log4jPattern main - This Is A Log Message ..!
    
  • Conversion Patterns where Date and Time matters: Sometimes it is critical to measure time in the log output. By default, the %d conversion character outputs the date and time in ISO8601 format. However, developers can use a date format specifier to format the date and time explicitly. For e.g.:
    • If developers need time granularity to milliseconds: [%p] %d{MM-dd-yyyy HH:mm:ss,SSS} %c %M - %m%n
      Output

      [INFO] 11-14-2017 20:36:01,331 com.jcg.log4j.Log4jPattern main - This Is A Log Message ..!
      
    • ISO8601 Date Format specifier: [%p] %d{ISO8601} %c %M - %m%n
      Output

      [INFO] 2017-11-14 20:37:21,116 com.jcg.log4j.Log4jPattern main - This Is A Log Message ..!
      
    • Using DATE format specifier: [%p] %d{DATE} %c %M - %m%n
      Output

      [INFO] 14 Nov 2017 20:38:36,355 com.jcg.log4j.Log4jPattern main - This Is A Log Message ..!
      
    • Using ABSOLUTE date format specifier: [%p] %d{ABSOLUTE} %c %M - %m%n
      Output

      [INFO] 20:47:49,096 com.jcg.log4j.Log4jPattern main - This Is A Log Message ..!
      
  • Conversion Patterns where Thread Context matters: For debugging multi-threaded applications, Log4j provides the following conversion characters:
    • %t: Thread Name
    • %x: Thread’s Nested Diagnostic Context
    • %X: Thread’s Mapped Diagnostic Context

    Pattern: [%p] %d [%t] %x %c %M - %m%n
    Output

    [INFO] 2017-11-14 21:24:29,147 [main] com.jcg.log4j.Log4jPattern main - This Is A Log Message ..!
    

That’s all for this post. Happy Learning!!

6. Conclusion

That’s all for getting the developers started with the Log4j example. We will look into more features in the next posts. I hope this article served you whatever you were looking for. Developers can download the sample application as an Eclipse project in the Downloads section.

7. Download the Eclipse Project

This was an example of Log4j Conversion Pattern Example.

Download
You can download the full source code of this example here: Log4jConversionPattern

Yatin

An experience full-stack engineer well versed with Core Java, Spring/Springboot, MVC, Security, AOP, Frontend (Angular & React), and cloud technologies (such as AWS, GCP, Jenkins, Docker, K8).
Subscribe
Notify of
guest

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

0 Comments
Oldest
Newest Most Voted
Inline Feedbacks
View all comments
Back to top button