Working with Log4J Basics – A Log4J Tutorial

DeeKay December 28, 2016 at 9:08 pm · APIs, Tutorial

Introduction

Here is your Basic Log4J tutorial helps you to setup Log4J in your application. Log statements placed in your code will work as a high level debugging mechanism for your application. Here I’m saying the logging mechanism as high level debugging mechanism, as low level debug mechanism is debugging the code step-by-step using IDE debugger.

There are different loggings APIs available to integrate logging in your source code. From all these APIs Apache LOG4J API is most widely used Logging API in java code base. However adding a large number of log statements in the code would impact the performance of the application, so it is always good to use minimum log statements and should be placed only in critical part of the code.

LOG4J API enables logging at the runtime without modifying any of the application’s binary i.e. compiled code. LOG4J is designed in such a way that it can be turned-off and turned-on by editing the configuration file for LOG4J, without touching the application binary. This will also allow us to keep the log statements in the code as it is in the delivered code, without incurring any heavy performance cost.

Downloading and Adding LOG4J API to Class Path

Download the latest and updated version of LOG4J API from the below location:

http://logging.apache.org/log4j/1.2/download.html

To ensure the integrity of the downloaded file use md5sum. In Linux shell, you can do it by below command –

md5sum logging-log4j-1.2.14.zip

When you execute the above command you will get a number which you have to verify with the number on the homepage. Some web browsers such as Firefox provides the plug-in md hash tool, which directly checks the downloading file for md5sum.

Once the LOG4J jar file downloaded, you have to add the jar file to the classpath of the project.
In eclipse IDE you can do it by right-clicking on the project folder and going to properties window –> Java Build Path –> Libraries –>Add External JARs –> select the downloaded Log4J jar file.

LOG4J Basics

Basic 3 components of Log4J are:

  1. Loggers
  2. Appenders
  3. Layouts

These 3 components together work to log messages depending on the message type and level. It also allows controlling these messages at runtime by enabling/disabling specific log message type.

Loggers

Loggers are the named entities. Logger names are case sensitive and they follow the hierarchical rule. Root Logger in the Log4J is the parent of all loggers and it resides at the top of the logger hierarchy. Root Logger exists always and it cannot be retrieved by name. Root logger is retrieved as below:

Logger rootLogger = Logger.getRootLogger ()

Logger has below pre defined log levels:

  • TRACE
  • DEBUG
  • INFO
  • WARN
  • ERROR
  • FATAL

Logging request is done by invoking one of the printing methods of the logger instance. These printing methods are debug, info, warn, error, fatal and log. These printing methods determine the level of the logging.

Appenders

Log4J allows us to print the log statements at multiple locations. In Log4J language, this output destination is called as an appender. Log4J supports below appenders in Log4J 1.2 –

  • File appender
  • Console appender
  • GUI Component appender
  • SMTP appender
  • Rolling file appender
  • JDBC appender
  • Telnet appender
  • Remote Socket appender
  • JMS appender
  • NT Event Log appender
  • Syslog appender

In Log4J it is possible to activate more than one appenders.

Layouts

The output format of the Log statements is called as Layouts in the Log4J. The user can customize the output format by associating the layout with an appender. The layout is responsible for formatting the logging request according to the user’s wishes, whereas an appender takes care of sending the formatted output to its destination.

The PatternLayout, part of the standard log4j distribution, lets the user specify the output format according to conversion patterns similar to the C language printf function.

For example, the PatternLayout with the conversion pattern “%r [%t] %-5p %c – %m%n” will output something akin to:

176 [main] INFO  com.kodehelp.log – This is the Log output.

For more details on Layouts please refer below URL –
http://logging.apache.org/log4j/docs/api/org/apache/log4j/PatternLayout.html

Configuring LOG4j in the Application

Log4J can be configured by below 3 ways:

  1. Programmatically
  2. Log4j.properties file (Java Properties)
  3. Log4j.xml file

Log4J gives full flexibility of configuring the logging programmatically. Let’s see an example to configure logging programmatically in java code.


/**********************************************************************************
 * Created on Nov, 2004 copyright(c) http://kodehelp.com All Rights Reserved.
 **********************************************************************************/
package com.kodehelp.log4j.example;

import org.apache.log4j.BasicConfigurator;
import org.apache.log4j.Logger;

/**
 * @author http://kodehelp.com
 *
 */
public class ConfigureLog4J {
	/*
	 * Define a static logger variable so that it references the
	 * Logger instance named "ConfigureLog4J".
	 */
	 static Logger logger = Logger.getLogger(ConfigureLog4J.class);
	/**
	 * @param args
	 */
	public static void main(String[] args) {
		 // Set up a simple configuration that logs on the console.
	     BasicConfigurator.configure();
	     logger.info("Entering application.");
	     //Write your code logic
	     logger.info("Exiting application.");
	}
}

The invocation of the BasicConfigurator.configure method creates a rather simple log4j setup. This method is hardwired to add to the root logger a ConsoleAppender. The output will be formatted using a PatternLayout set to the pattern “%-4r [%t] %-5p %c %x – %m%n”.
The output for the above logger code is


0 [main] INFO com.kodehelp.log4j.example.ConfigureLog4J  - Entering application.
16 [main] INFO com.kodehelp.log4j.example.ConfigureLog4J  - Exiting application.

Configuring with Log4j.xml
You can configure the Log4J in your application by creating the Log4J.xml file in the src directory of the application.

Below is the sample log4j.xml file

<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE log4j:configuration SYSTEM "log4j.dtd" >
<log4j:configuration>
 <appender name="stdout" class="org.apache.log4j.ConsoleAppender">
	 <layout class="org.apache.log4j.PatternLayout">
	  <param name="ConversionPattern" value="%d{ABSOLUTE} %5p %c{1}:%L - %m%n"/>
	 </layout>
 </appender>
 <root>
	<priority value="debug"></priority>
	<appender-ref ref="stdout"/>
 </root>
</log4j:configuration>

Once you have the proper log4j.xml file created in the src directory of your project, you can start using the logger as shown in the below example –


/**********************************************************************************
 * Created on Nov, 2004 Copyright(c) http://kodehelp.com All Rights Reserved.
 **********************************************************************************/
package com.kodehelp.log4j.example;

import org.apache.log4j.Logger;

/**
 * @author http://kodehelp.com
 *
 */
public class ConfigureLog4J {
	/*
	 * Define a static logger variable so that it references the
	 * Logger instance named "ConfigureLog4J".
	 */
	 static Logger logger = Logger.getLogger(ConfigureLog4J.class);
	/**
	 * @param args
	 */
	public static void main(String[] args) {
		 // Set up a simple configuration that logs on the console.
	     logger.info("Entering application.");
	     //Write your code logic
	     logger.info("Exiting application");
	}
}

Output for the above example is –


14:01:58,308  INFO ConfigureLog4J:25 - Entering application.
14:01:58,339  INFO ConfigureLog4J:27 - Exiting application