Log4j

log4j rootlogger example

In this example we shall talk about the rootlogger, which is a basic component in Log4j. Log4j a thread-safe and flexible logging library for Java, licensed under the Apache Software Foundation.

The basic components of the log4j architecture are the loggers, the appenders and the layouts. Loggers are used to log the messages, appenders to publish the messages to different outputs and layouts to format the log messages. All these components are configured in the log4j.properties file, which is placed in the application classpath.

The basic logger that sits at the top of the logger hierarchy is the rootlogger. RootLogger is a regular logger, although it cannot be assigned a null level and since it cannot have a parent, the getChainedLevel() API method always returns the value of the level field without walking the hierarchy. Also, the rootLogger cannot be retrieved by name. It can only be retrieved by invoking the static getRootLogger() API method of Logger. All other loggers are instantiated and retrieved with the class static getLogger(String name) API method of Logger, which takes the name of the desired logger as a parameter.

Below, we have created an example with a class that uses the rootlogger to log messages to the console.

Tip
You may skip project creation and jump directly to the beginning of the example below.

Our preferred development environment is Eclipse. We are using Eclipse Juno (4.2) version, along with Maven Integration plugin version 3.1.0. You can download Eclipse from here and Maven Plugin for Eclipse from here. The installation of Maven plugin for Eclipse is out of the scope of this tutorial and will not be discussed. We are also using the JDK 7_u_21.

Let’s begin,

1. Create a new Maven project

Go to File -> Project ->Maven -> Maven Project.

New Maven Project
New Maven Project – step 1

In the “Select project name and location” page of the wizard, make sure that “Create a simple project (skip archetype selection)” option is checked, hit “Next” to continue with default values.

New Maven Project 2
New Maven Project 2

In the “Enter an artifact id” page of the wizard, you can define the name and main package of your project. We will set the “Group Id” variable to "com.javacodegeeks.snippets.enterprise" and the “Artifact Id” variable to "log4jexample". The aforementioned selections compose the main project package as "com.javacodegeeks.snippets.enterprise.log4jexample " and the project name as "log4jexample". Hit “Finish” to exit the wizard and to create your project.

log4j example
log4j example

The Maven project structure is shown below:

log4j example structure
log4j example structure

    It consists of the following folders:

  • /src/main/java folder, that contains source files for the dynamic content of the application,
  • /src/test/java folder contains all source files for unit tests,
  • /src/main/resources folder contains configurations files,
  • /target folder contains the compiled and packaged deliverables,
  • the pom.xml is the project object model (POM) file. The single file that contains all project related configuration.

2. Add log4j dependency

Add the log4j dependency in Maven’s pom.xml file, by editing it at the “Pom.xml” page of the POM editor, as shown below:
 
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>com.javacodegeeks.snippets.enterprise</groupId>
	<artifactId>log4jexample</artifactId>
	<version>0.0.1-SNAPSHOT</version>
	<dependencies>
		<dependency>
			<groupId>log4j</groupId>
			<artifactId>log4j</artifactId>
			<version>1.2.17</version>
		</dependency>
	</dependencies>
</project>

As you can see Maven manages library dependencies declaratively. A local repository is created (by default under {user_home}/.m2 folder) and all required libraries are downloaded and placed there from public repositories. Furthermore intra – library dependencies are automatically resolved and manipulated.

3. Create the log4j.properties file

The log4j.properties file is placed under the resources folder of the project. This is where all logging components are configured. The rootLogger is set here, binded to a logging level and an appender. The rootlogger is always the logger configured in the log4j.properties file, so every child logger used in the application inherits the configuration of the rootlogger.

The logging levels are (from smaller to greater) : ALL, DEBUG, INFO, WARN, ERROR, FATAL, OFF. When a logging level is set, only messages belonging to this level or greater levels are printed.

Here, we use an appender to log messages to the console. It uses the org.apache.log4j.ConsoleAppender. It has a target attribute which is set to System.out and uses a layout for the logging messages. The org.apache.log4j.PatternLayout is used and the ConversionPattern is set to %d{dd/MMM/yyyy HH:mm:ss,SSS}- %c{1}: %m%n.

%d{dd/MMM/yyyy HH:mm:ss,SSS} is used to set the date pattern, %c{1} is used to print the class name, %m to print the message, and %n to leave an empty line.

log4j.properties

log4j.rootLogger = INFO, stdout

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{dd/MMM/yyyy HH:mm:ss,SSS}- %c{1}: %m%n

4. Create an Example class

Example.java class gets the rootLogger to log messages to the console. The logger is stated as a static field, initialized by the getRootLogger() API method of org.apache.log4j.Logger. Example.java class has a main method, where the user is asked to type number. The logger first logs messages of different levels, using info(Object message), warn(Object message), debug(Object message), error( Object message) and fatal(Object message) API methods of org.apache.log4j.Category.

Example.java:

package com.javacodegeeks.snippets.enterprise.log4jexample;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;

import org.apache.log4j.Level;
import org.apache.log4j.Logger;

public class Example {

	static Logger log = Logger.getRootLogger();

	public static void main(String[] args) throws IOException {
		System.out.println("===> Please enter a number:\n===>");
		BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
		int number = Integer.valueOf(br.readLine());
		log.info("Info : number is " + number);
		log.warn("Warning : number is " + number);
		log.debug("Debug : number is " + number);
		log.error("Error : number is " + number);
		log.fatal("Fatal : number is " + number);
	}
}

5. Run the application

Run the application. The result in the console will be something like the one below:

===> Please enter a number:
===>
2
30/Sep/2014 00:29:21,605- root: Info : number is 2
30/Sep/2014 00:29:21,659- root: Warning : number is 2
30/Sep/2014 00:29:21,659- root: Error : number is 2
30/Sep/2014 00:29:21,659- root: Fatal : number is 2

As you can see, since the log level is set to INFO, only info, warning, error and fatal messages are printed. You can change the logging level and see what happens.

6. Download the Eclipse Project

This was an example of Log4j rootlogger.

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

Theodora Fragkouli

Theodora has graduated from Computer Engineering and Informatics Department in the University of Patras. She also holds a Master degree in Economics from the National and Technical University of Athens. During her studies she has been involved with a large number of projects ranging from programming and software engineering to telecommunications, hardware design and analysis. She works as a junior Software Engineer in the telecommunications sector where she is mainly involved with projects based on Java and Big Data technologies.
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