Apache Log4j Logging Framework Tutorial, Loggers, Appenders,Layouts

From last few days I was thinking to write about a post on log4j framework and the problems that logo-apche-log4j-logging-frameworka developer faces during its configuration time because I also faced lot of problems when I started working on Apache log4j logging framework. In this post I am going to start from basic ,e.g what is a logging framework ? , Why it is required? How to Configure it in your application ? and most common exceptions that you will get during configuration. So, let’s start.

What is a Logging Framework ?
In simple terms logging is an activity to capture all the junk/temporary data that is generated while an application is running. Why I am saying it as junk because it is like temporary data that you will store it for some-time and after that it will become redundant for you. Sometimes this logged data becomes very useful if we use it properly, e.g the most common scenario for that logging is the complete trace of an exception while an application is running. Now suppose a scenario where your application suddenly stopped running or it is behaving randomly, then in this case if you are not logging the data then it is almost impossible for a developer to track the issue. That’s why it is highly recommended to use a logging framework in your java application.
Java provides a lot of logging frameworks like log4j, slf4j,Simple Log, Commons Logging etc. For complete list you can refer here. So, now again which one to choose it also depends on lot of factors and more specifically on your application requirements.

In this post we will focus on Apache log4j framework. So, let’s first have a look at the basic definition of log4j:
Apache Log4j Logging Framework:
Log4j is a java logging framework licensed under Apache GNU. Best thing about log4j is that it is very simple to configure and require no extra knowledge except java and xml. Log4j supports different levels of logging like TRACE, DEBUG, INFO, WARN, ERROR, and FATAL all of them defined in org.apache.log4j.Level class, you can choose any of the level as per your application requirement. The order of logging level that is mentioned earlier is very important to understand because it can impact logging of your application.log-level-rule-apache-log4j-logging-framework

Let’s see how , now suppose if you set the logging level at INFO then that means logging framework will log all the messages that are INFO , WARN, ERROR and FATAL. So, basic definition here is log4j logging framework will log all the messages of that level and all the levels below it. Log4j also provides you flexibility to define your own log levels but it is not recommended. You can achieve the same thing in other way , that we will discuss in some other post. For more reference have a look at below image.log-level-apache-log4j-logging-framework

Log4j Framework Components:
Apache Log4j Logging framework has 3 main components and each component has its own specific role. In order to master log4j it is very important that we should understand role of these components and there variations which one to use when. All these three components integrates together and provide you flexibility on what type of messages you want to log , where to log them , in which format to log them.log4j-components-apache-log4j-logging-framework

1. Loggers :
Logger is the heart of Apache Log4j Logging Framework some people call it backbone of framework. With logger you can define logging level in your application. An application can have as many loggers as many classes they have and each class can instantiate its own logger (not mandatory) because you can use the same logger throughout the application or can use your parent class logger. But this thing has a major drawback, suppose if you used common logger across the application then during the debugging time it will be impossible for you to identify the source of that message. So, its recommended that each class should have its own logger.
You can create a logger for any class like this-

Logger myLogger=Logger.getLogger(“com.techidiocy.FirstLogger”);

Here, we have an instantiated a logger for my class com.techidiocy.FirstLogger. In the getLogger() method you can pass any string but it is recommended that you should pass the fully qualified class name so that during debugging time you can easily identify the source of message.
The other important thing that comes under Logger , is the log level that we are setting , as we have already discussed those in our previous header (Apache Log4j Logging Framework).

2. Appenders and Layouts :
Once you have the message that you want to log , the next question comes here is where exactly you want to log these messages and in which format, appenders and layout of Apache log4j logging framework define those criteria for you. You can configure as many appender you want with your logger and after that each of your log message will go to each of the appenders and from their appender will send them to desired destination. Here, destination can be anything like a file , a console, remote servers, database etc .

Appenders also share a full fledge parent child relationship that means if you have a logger P that have appender A-P and there is a child logger C that have appender A-C , then whenever there is a message to be logged  for logger C ,it will send to appenders of logger C and all of its ancestors in the hierarchy that means A-P will also receive the message to append. This phenomenon is known as Appender Additivity.

If you don’t want this behavior and want to avoid the duplications of logs then you can override the additive flag of the loggers. Below is more exact definition of Appender Additivity from Apache log4j logging framework.

Layout are the components that will decide in what format your message will be displayed in your required destinations. It is completely customizable and a developer can decide in what format they want to see there log messages. By default PatternLayout is available to us and it will bind to our logger. PatternLayout display the in below mentioned format.

"%r [%t] %-5p %c - %m%n"

And its final output will look like.

0 [main] INFO com.techidiocy.MyFirstLogger –This is my first info level statement.

Below is the explanation of each of the field.
The first field is the number of milliseconds elapsed since the start of the program. The second field is the thread making the log request. The third field is the level of the log statement. The fourth field is the name of the logger associated with the log request. The text after the ‘-‘ is the message of the statement.
3. Configuration :
Third component basically talks about how do you want to manage loggers , appenders , layouts and other properties in your application. You can manage these components in 3 ways , Programmatically , XML File and properties file (key value) pair. 1st approach is not recommended because it is very difficult to manage all the loggers programmatically and as soon as your application starts expanding it will become cumbersome for you to manage those.
Recommended approaches are either use XML file or Properties file , so that configuration can be changed without impacting the application and it will be independent also.

Till now we have covered all the basic details associated with Apache log4j logging framework. In the next post we will see how to initialize the loggers in all the three ways and will do our hands dirty with some coding.

All the images belong to there respective owners.
Image Source : jumpingbean.co.za ,programming-free.com ,logging.apache.org



Saurabh Jain

A Developer working on Enterprise applications ,Distributed Systems, Hadoop and BigData.This blog is about my experience working mostly on Java technologies ,NoSQL ,git , maven and Hadoop ecosystem.

Share and Enjoy

  • Facebook
  • Twitter
  • Delicious
  • LinkedIn
  • StumbleUpon
  • Add to favorites
  • Email
  • RSS
Add Comment Register

Leave a Reply

Your email address will not be published. Required fields are marked *

You may use these HTML tags and attributes: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <s> <strike> <strong>