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:
- Loggers
- Appenders
- 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 –
https://logging.apache.org/log4j/1.2/apidocs/org/apache/log4j/PatternLayout.html
Configuring LOG4j in the Application
Log4J can be configured by below 3 ways:
- Programmatically
- Log4j.properties file (Java Properties)
- 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) https://kodehelp.com All Rights Reserved.
**********************************************************************************/
package com.kodehelp.log4j.example;
import org.apache.log4j.BasicConfigurator;
import org.apache.log4j.Logger;
/**
* @author https://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) https://kodehelp.com All Rights Reserved.
**********************************************************************************/
package com.kodehelp.log4j.example;
import org.apache.log4j.Logger;
/**
* @author https://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
Configuring with log4j.properties
If the Log4J API doesn’t find the log4j.xml file it will try to look for log4j.properties file in the src directory. Below is the sample log4j.properties file to configure logger in the application.
#Log messages to Console
log4j.appender.stdout=org.apache.log4j.ConsoleAppender
log4j.appender.stdout.Target=System.out
log4j.appender.stdout.layout=org.apache.log4j.PatternLayout
log4j.appender.stdout.layout.ConversionPattern=%d{ABSOLUTE} %5p %c{1}:%L - %m%n
log4j.rootLogger=debug, stdout
If you execute the same code using the log4j.properties file you will get the log output on the console as
14:01:58,308 INFO ConfigureLog4J:25 - Entering application.
14:01:58,339 INFO ConfigureLog4J:27 - Exiting application
log4j.xml versus log4j.properties
Properties can be defined by a properties file or by an XML file. Log4j looks for a file named log4j.xml and then for a file named log4j.properties. Both must be placed in the src folder. The property file is less verbose than an XML file. The XML requires the log4j.dtd to be placed in the source folder as well. The XML requires a dom4j.jar which might not be included in older Java versions.
The properties file does not support some advanced configuration options like Filters, custom ErrorHandlers and a special type of appenders, i.e. AsyncAppender. ErrorHandlers defines how errors in log4j itself are handled, for example badly configured appenders. Filters are more interesting. From the available filters, I think that the level range filter is really missing for property files. This filter allows defining that an appender should receive log messages from Level INFO to WARN. This allows splitting log messages across different logfiles. One for DEBUGGING messages, another for warnings.
The property appender only supports a minimum level. If you set it to INFO, you will receive WARN, ERROR and FATAL messages as well.