Java ProgrammingLearn How to use log4j in Java

Learn How to use log4j in Java

How-to-use-log4j-in-Java_KaushikPal-740X296

A logging API or library is very important for the development of applications in Java. Actually, log4j is nothing but an API. It is originally based on the Java programming language, though it has been ported to a variety of other programming languages, such as C++, Ruby, Eiffel, C, Python and Perl. But here, we’ll discuss about the version for Java.

Log4j can be relied upon as it is very adaptable and quick. It is now licensed under the Apache Software License. Also, the user can customise and configure the settings of the API through configuration files which can be used directly during runtime. This API offers different kinds of mechanisms for different destinations. These destinations include consoles, UNIX Syslog, a database or a file. Also, it prioritises the logging processes for quicker and more efficient logging. Using log4j API is very easy as most of the work is done by proper configuration of log4j in the code.

A little back ground:
Log4j is a very flexible logging library for development of applications in Java programming language. It consists of three parts which is the layouts, appenders and the loggers. The layouts are used for changing the logging information according to different styles of formatting, while appenders are used for the transportation of the information to different places. The logger is important for actually receiving and copying the logging data.

Log4j was developed during early 1996. It was actually designed for the Secure Electronic Marketplace for Europe (or E.U. SEMPER) project as a tracing API. However, this simple tracing API evolved into a complete logging library when a lot of alterations were done on it. Today, this logging package is licensed under the open-source Apache Software License, which is a part of the Open-Source initiative. The source code, documentations and class files can be acquired from their website.

Why log4j is important?
Logging is very important for the development and testing of an application. Every application needs a good logging API because it is essential for debugging, testing and troubleshooting the application. Log4j is such a complete logging package, one which allows better and faster application development. It allows many different functions that other logging packages do not allow.

Another thing that makes log4j very important is that its settings can be configured easily during runtime through external configuration files. This aspect makes it very adaptable and the user can easily bend it according to his or her needs.

What are the features?
There are many features of log4j which sets it up a notch when compared to other logging packages. It is due to these features that log4j is so dependable and useful.

Firstly, it is safe from threads. Also, it is designed for extremely quick development of the application being made. It can use multiple appenders for each logger, making the logging process much faster than other logging packages. Some other features are listed below:

  • The behaviour while logging can be predefined by configuration files.
  • It can use the features of internationalization.
  • The facility set can be easily expanded.
  • The hierarchy of the package is that of named logger.
  • The Java Exceptions arising during the development can be tackled easily.
  • The layout class can be used for changing the format of the output of the log.
  • It can utilise many levels while logging, for example, INFO, WARN, FATAL, ALL, TRACE, ERROR and DEBUG.
  • The appender can be used for changing the target for the logging information.

Advantages and disadvantages
We all know that logging is one of the most important things while developing software. Thus, a good logging package and a nicely written logging code are very crucial for the development of the application. Log4j is a very good logging library which allows more efficient and faster application development by faster debugging, better code saving and by saving the details of software runtime.

However, logging is not always good. While it can speed up the development cycle of the application, it can actually slow down the software itself. However, log4j is being developed constantly in order to counter these issues.

It is quite simple to use, and also very powerful at the same time.

Installation & configuration
Log4j package comes as an open source project. So the full source code, documentation and class files can be downloaded. For installation, the (.zip) or (.gz) file can also be downloaded separately.

Now, follow the steps below for installation.

  • Extract the content of the (.zip)/(.gz) file in a directory, preferably under /user/local. During extraction, it will create its own hierarchy.
  • Log4j can be plugged in with other essential features like mailing, message services, xml data format etc. So, the required packages for these functionalities can also be installed. But this is optional.
  • Set the CLASSPATH and PATH variables properly to point log4j jars. Sample classpath and path setting are shown below.

[code]
/usr/local/apache-log4j-2.6.1
$ export CLASSPATH=$CLASSPATH:/usr/local/apache-log4j-2.6.1/apache-log4j-2.6.1.jar
$ export PATH=$PATH:/usr/local/apache-log4j-2.6.1/
[/code]

After installation, configuration of log4j.properties file is another important task to be completed. It is the configuration file, containing data as key/value pairs. This file is also set at the CLASSPATH. It contains root logger information, appender details and layout information. Following is a sample log4j.properties file.

[code]
# This is root logger information with appender X. It can be a FILE appender
log4j.rootLogger = DEBUG, X
# This is appender details with X set as File appender
log4j.appender.X=org.apache.log4j.FileAppender
# This is layout information for appender X
log4j.appender.X.layout=org.apache.log4j.PatternLayout
log4j.appender.X.layout.conversionPattern=%m%n
[/code]

Now your installation and configuration is complete, and we will check an example how to use the logging framework with Java application.

Sample application by using log4j

In this example we will perform three tasks to get the output. Let us check one by one.

First Step – Set up log4j.properties file

This is the log4j properties file with FILE appender. It defines the FILE name, appender information and layout plan.

Listing 1: Sample log4j properties file

[code]
# Root logger information with FILE appender
log = /usr/home/log4j
log4j.rootLogger = DEBUG, FILE
# FILE appender information with log.out as the output file
log4j.appender.FILE=org.apache.log4j.FileAppender
log4j.appender.FILE.File=${log}/log.out
# Defining layout information with new line character
log4j.appender.FILE.layout=org.apache.log4j.PatternLayout
log4j.appender.FILE.layout.conversionPattern=%m%n
[/code]

Second Step- Write the Java code and integrate log4j

This is the Java application for printing log information. First, it assigns the class name with the logger. And, then it captures different log level information as per requirement. We have shown debug, info, warn and error information. These levels have to be implemented at proper situations for better tracking.

Listing 2: Sample Java application with log4j

import org.apache.log4j.Logger;
import org.apache.log4j.PropertyConfigurator;
import java.io.*;
import java.util.*;
public class log4jDemo{
/*Assign the class name to the logger */
static Logger log = Logger.getLogger(log4jDemo.class);
public static void main(String[] args)
{
/*Print log level information*/
log.debug("This is debug log");
log.info("This is info log");
log.warn("This is warning log");
log.error("This is error log");
}
}

Third Step – Compile and runt the application

Now, the final step is to compile and run the Java application. Once the application is executed, it will print the log level information in a file named as log.out as shown below.

This is debug log
This is info log
This is warning log
This is error log

In actual scenario, the output file will capture relevant log information for further analysis.

Conclusion:
Every application that is being developed in some kind of programming language needs a good and dependable logging package. In Java, log4j aims to be that logging library. Log4j was originally developed for the SEMPER project, as it was a very high priority project which needed a good logging API. However, as time flew by, log4j became an entire package of logging APIs. Now, it is one of the most popular logging libraries for Java. It is so powerful that it has been ported to work with many other programming languages. Also, its source code is completely open source, so it can be modified according to the user’s preferences.

2 COMMENTS

  1. Glad you are writing about Log4j 2 (and not Log4j 1.2 which is End Of Life).
    However, please review the example configuration and Java code since they seem to be for Log4j 1.2.

LEAVE A REPLY

Please enter your comment!
Please enter your name here

Exclusive content

- Advertisement -

Latest article

21,501FansLike
4,106FollowersFollow
106,000SubscribersSubscribe

More article

- Advertisement -