Home » Enterprise Java » Log4j » log4j – Appender Example

About Armando Flores

Armando Flores
Armando graduated from from Electronics Engineer in the The Public University Of Puebla (BUAP). He also has a Masters degree in Computer Sciences from CINVESTAV. He has been using the Java language for Web Development for over a decade. He has been involved in a large number of projects focused on "ad-hoc" Web Application based on Java EE and Spring Framework.

log4j – Appender Example

In this post, we are going to discuss about log4j appenders and how you configure it using an log4j.xml file.

1. What is log4j?

log4j is a tool to help the programmer output log statements to a variety of output targets.

In case of problems with an application, it is helpful to enable logging so that the problem can be located. With log4j it is possible to enable logging at runtime without modifying the application binary. The log4j package is designed so that log statements can remain in shipped code without incurring a high performance cost. It follows that the speed of logging (or rather not logging) is capital.

At the same time, log output can be so voluminous that it quickly becomes overwhelming. One of the distinctive features of log4j is the notion of hierarchical loggers. Using loggers it is possible to selectively control which log statements are output at arbitrary granularity.

log4j is designed with three goals in mind: reliability, speed and flexibility. There is a tight balance between these requirements. We believe that log4j strikes the right balance.

log4j has three main components: loggers, appenders and layouts. These three types of components work together to enable developers to log messages according to message type and level, and to control at runtime how these messages are formatted and where they are reported.

1.1 What are log4j appenders?

log4j allows logging requests to print to multiple destinations. In log4j speak an output destination is called an appender. Currently, appenders exist for the console, files, Swing components, remote socket servers, JMS, NT Event Loggers, and remote UNIX Syslog daemons. Log4j allows attaching multiple appenders to any logger. Appenders can be added to and removed from a logger at any time. A logger can make use of one and only one level.

1.2 log4j layouts

More often than not, users wish to customize not only the output destination but also the output format. This is accomplished by associating a 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 formatted output to its destination. Most layouts are not designed to be shared by multiple appenders. It follows that each appender must have its own “private” layout.

A common layout called the PatternLayout, part of the standard log4j distribution, lets the user specify the output format according to conversion patterns similar to the C language’s printf function. For example, a PatternLayout with the conversion pattern “%r [%t] %-5p %c – %m%n” will output something akin to:

199 [main] INFO com.foo.Bar - Hello there.

The first field is the number of milliseconds elapsed since the start of the program. The second field is the thread that executed 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.

1.3 log4j – Configuration scripts

The log4j environment is fully configurable programmatically. However, it is far more flexible to configure log4j using configuration files. Currently, configuration files can be written Java properties (key=value) format or in XML.

Let’s see an example of how easy is to configure appenders using a configuration script.

log4j.xml

<?xml version="1.0" encoding="UTF-8" ?>
<!DOCTYPE log4j:configuration SYSTEM "log4j.dtd">
<log4j:configuration debug="false" xmlns:log4j="http://jakarta.apache.org/log4j/">

	<!-- Console Appender -->
	<appender name="console" class="org.apache.log4j.ConsoleAppender">
		<layout class="org.apache.log4j.PatternLayout">
			<param name="ConversionPattern" value="%d{yyyy-MM-dd HH:mm:ss} %-5p %c{1}:%L - %m%n" />
		</layout>
	</appender>

	<!-- File Appender -->
	<appender name="file" class="org.apache.log4j.RollingFileAppender">
		<param name="append" value="false" />
		<param name="maxFileSize" value="10KB" />
		<param name="maxBackupIndex" value="5" />
		<param name="file" value="/Users/afibarra/Tmp/FooBar.log" />
		<layout class="org.apache.log4j.PatternLayout">
			<param name="ConversionPattern" value="%d{yyyy-MM-dd HH:mm:ss} %-5p %c{1}:%L - %m%n" />
		</layout>
	</appender>

	<!-- Foo package -->
	<logger name="com.javacodegeeks.examples.log4jappenders.foo">
		<level value="INFO" />
		<appender-ref ref="console" />
		<appender-ref ref="file" />
	</logger>

	<!-- Bar package -->
	<logger name="com.javacodegeeks.examples.log4jappenders.bar">
		<level value="WARN" />
		<appender-ref ref="console" />
		<appender-ref ref="file" />
	</logger>

	<!-- Root logger option -->
	<root>
		<level value="DEBUG" />		
		<appender-ref ref="console" />
		<appender-ref ref="file" />
	</root>

</log4j:configuration>

Here, he have defined two of the most used appenders:

2. Executing some code

FooBean.java

package com.javacodegeeks.examples.log4jappenders.foo;

import org.apache.log4j.Logger;

public class FooBean {
	private static final Logger logger = Logger.getLogger(FooBean.class);
	
	public void sayHello() {
		logger.debug("Hello there from FooBean class!");
		
		logger.info("Hello there from FooBean class!");
	}
}

BarBean.java

package com.javacodegeeks.examples.log4jappenders.bar;

import org.apache.log4j.Logger;

public class BarBean {
	private static final Logger logger = Logger.getLogger(BarBean.class);

	public void sayHello() {
		logger.info("Hello there from BarBean class!");

		logger.warn("Hello there from BarBean class!");
	}
}

App.java

package com.javacodegeeks.examples.log4jappenders;

import org.apache.log4j.Logger;

import com.javacodegeeks.examples.log4jappenders.bar.BarBean;
import com.javacodegeeks.examples.log4jappenders.foo.FooBean;

public class App {
	private static final Logger logger = Logger.getLogger(App.class);

	public static void main(String[] args) {
		FooBean fooBean = new FooBean();
		BarBean barBean = new BarBean();

		logger.debug("Hello there from App class!");

		fooBean.sayHello();
		barBean.sayHello();
	}
}

The output of the command java com.javacodegeeks.examples.log4jappenders.App should be similar to:

2014-08-16 19:25:48 DEBUG App:15 - Hello there from App class!
2014-08-16 19:25:48 INFO  FooBean:11 - Hello there from FooBean class!
2014-08-16 19:25:48 INFO  FooBean:11 - Hello there from FooBean class!
2014-08-16 19:25:48 WARN  BarBean:11 - Hello there from BarBean class!
2014-08-16 19:25:48 WARN  BarBean:11 - Hello there from BarBean class!
RollingFileAppender - Output

RollingFileAppender – FooBar.log file

FooBar.log file content

RollingFileAppender – FooBar.log file content

3. Download the Eclipse project of this tutorial:

This was an example of how to set appenders for the log4j library.

Download
You can download the full source code of this example here : log4jappenders.zip
(No Ratings Yet)
Start the discussion Views Tweet it!

Do you want to know how to develop your skillset to become a Java Rockstar?

Subscribe to our newsletter to start Rocking right now!

To get you started we give you our best selling eBooks for FREE!

 

1. JPA Mini Book

2. JVM Troubleshooting Guide

3. JUnit Tutorial for Unit Testing

4. Java Annotations Tutorial

5. Java Interview Questions

6. Spring Interview Questions

7. Android UI Design

 

and many more ....

 

Receive Java & Developer job alerts in your Area

 

Leave a Reply

avatar
  Subscribe  
Notify of