Using Log4j with Codenvy

Log4j is a Reliable, Fast and Flexible Logging Framework .It is an open source Framework published under the terms of the Apache Software License version 2.0.
It allows the developer to control which log statements are output with arbitrary granularity. It is fully configurable at runtime using external configuration files.

Log4j has three main components

1. Loggers
2. Appenders
3. Layouts

Loggers :

Loggers are responsible for logging the information.
There are different levels of logging.The set of Logging levels are

  • ALL
  • TRACE
  • DEBUG
  • INFO
  • WARN
  • ERROR
  • FATAL
  • OFF

These Levels are defined in org.apache.log4j.Level Class. To Create a Logging Instance in a Class.Make use of Logger Class as follows.

Logger.getRootLogger(ClassName) method.

Example: HelloWorld.java

package com.codenvy;

import org.apache.log4j.Logger;

/**
 * Hello world!
 *
 */
public class HelloWorld {
	private static Logger logger = Logger.getLogger(HelloWorld.class);

	public boolean sayHello() {
		try{
			logger.trace("HelloWorld");
			logger.debug("HelloWorld");
			logger.info("HelloWorld");
			logger.warn("HelloWorld");
			logger.error("HelloWorld");
			logger.fatal("HelloWorld");

		}catch (Exception e) {
			// TODO: handle exception
			e.printStackTrace();
			return false;
		}

		return true;
	}

	public static void main(String[] args) {
		new HelloWorld().sayHello();
	}
}

Output Console :

TRACE - HelloWorld
DEBUG - HelloWorld
INFO  - HelloWorld
WARN  - HelloWorld
ERROR - HelloWorld
FATAL - HelloWorld

For Executing the Above java class you need log4j.jar and log4j.properties in Project Classpath.

Log4j.properties will be explained the later sections..

Appenders :

Appenders are responsible for Appending the log information to different Types persistent locations.

Types of appenders available in Log4j Framework:

  • AsyncAppender
  • ConsoleAppender
  • DailyRollingFileAppender
  • ExternallyRolledFileAppender
  • FileAppender
  • JDBCAppender
  • JMSAppender
  • LF5Appender
  • NTEventLogAppender
  • NullAppender
  • RewriteAppender
  • RollingFileAppender
  • SMTPAppender
  • SocketAppender
  • SocketHubAppender
  • SyslogAppender
  • TelnetAppender
  • WriterAppender

Appenders can be configured in the log4j.properties file or we can write our own custom appender by Implementing the Appender Interface.

Layouts :

An Appender uses a Layout to format a LogEvent into a form that meets the needs of whatever will be consuming the log event.

Types of Layouts are as follows:

  • DateLayout
  • EnhancedPatternLayout
  • HTMLLayout
  • PatternLayout
  • SimpleLayout
  • XMLLayout

To Create a Custom Layout user need to extend org.apache.log4j.Layout class.

The Log4j.properties file used in the above example is as follows.

Log4j.properties :
# Root logger
log4j.rootLogger=Trace,stdout

# ConsoleAppender
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=%-5p - %m%n
# Root logger
log4j.rootLogger=Trace, stdout

In the above line we can specify the log level,Here i given the level as Trace.It means all the log levels above the Trace will be appended to the Appender.

If the rootLogger is specified as log4j.rootLogger=Info, stdout

The output of the HelloWorld class is as follows

Console Output :

INFO  - HelloWorld
WARN  - HelloWorld
ERROR - HelloWorld
FATAL - HelloWorld
log4j.appender.stdout=org.apache.log4j.ConsoleAppender

The above line specifies the Appender type.Which outputs the log information to the console.

Here we can make use of different and Multiple Appenders to a Single Application

# Root logger
log4j.rootLogger=Trace,stdout,file
# ConsoleAppender
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=%-5p - %m%n

# RollingFileAppender
log4j.appender.file=org.apache.log4j.RollingFileAppender
log4j.appender.file.File=/logs/loging.log
log4j.appender.file.MaxFileSize=1MB
log4j.appender.file.MaxBackupIndex=1
log4j.appender.file.layout=org.apache.log4j.PatternLayout
log4j.appender.file.layout.ConversionPattern=%d{yyyy-MM-dd HH:mm:ss} %-5p %c{1}:%L - %m%n

The RollingFileAppender output will be written to /usr/app/log/loging.log

logging.log :

2013-07-17 01:34:45 INFO  HelloWorld:13 - HelloWorld
2013-07-17 01:34:45 WARN  HelloWorld:14 - HelloWorld
2013-07-17 01:34:45 ERROR HelloWorld:15 - HelloWorld
2013-07-17 01:34:45 FATAL HelloWorld:16 - HelloWorld

Project Structure

project_structure

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>Log4j_Tutorial</groupId>
	<artifactId>Log4j_Tutorial</artifactId>
	<version>0.0.1-SNAPSHOT</version>
	<packaging>jar</packaging>

	<name>Log4j_Tutorial</name>
	<url>http://maven.apache.org</url>

	<properties>
		<project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
	</properties>

	<dependencies>
		<dependency>
			<groupId>junit</groupId>
			<artifactId>junit</artifactId>
			<version>3.8.1</version>
			<scope>test</scope>
		</dependency>
		<dependency>
			<groupId>log4j</groupId>
			<artifactId>log4j</artifactId>
			<version>1.2.17</version>
		</dependency>
	</dependencies>

	<build>
		<plugins>
			<plugin>
				<groupId>org.apache.maven.plugins</groupId>
				<artifactId>maven-compiler-plugin</artifactId>
				<version>2.3.2</version>
				<configuration>
					<source>1.6</source>
					<target>1.6</target>
				</configuration>
			</plugin>

			<plugin>
				<groupId>org.apache.maven.plugins</groupId>
				<artifactId>maven-jar-plugin</artifactId>
				<version>2.4</version>
				<configuration>
					<archive>
						<manifest>
							<addClasspath>true</addClasspath>
							<mainClass>com.codenvy.HelloWorld</mainClass>
							<classpathPrefix>lib/</classpathPrefix>
						</manifest>
					</archive>
				</configuration>
			</plugin>
			<plugin>
				<groupId>org.apache.maven.plugins</groupId>
				<artifactId>maven-dependency-plugin</artifactId>
				<version>2.5.1</version>
				<executions>
					<execution>
						<id>copy-dependencies</id>
						<phase>package</phase>
						<goals>
							<goal>copy-dependencies</goal>
						</goals>
						<configuration>
							<includeGroupIds>log4j</includeGroupIds>
							<outputDirectory>${project.build.directory}/lib/</outputDirectory>
						</configuration>
					</execution>
				</executions>
			</plugin>

		</plugins>
	</build>
</project>

Features of Log4j Framework

1. Useful for debugging the large Applications.
2. Log4j is Thread Safe and easy to configure.
3. Supports multiple appenders for single Logger.
4. supports internationalization.
5. Optimised for speed.
6. Logging behaviour can be changed at runtime.

Drawbacks

1.It can slow down an application. If too verbose, it can cause scrolling blindness.