Log4j

July 20, 2007 at 12:34 am | In Java, Technology | 3 Comments

 

Intro

Log4J is a popular logging services for java. It was created by the Apache Software Foundation (ASF). Being one of the projects under ASF, it is a open source project, developed by programmers globally and received contribution from around the world.

It is grouped under the Apache's Logging Services http://logging.apache.org/index.html which provides cross language services for application debugging. It is bundled together with Apache 2.0 license. http://en.wikipedia.org/wiki/Apache_License

 

Why use logging?

Why use logging in the first place? We can always do a

System.out.println(“Log message”); anywhere we like and it is still a logging message.

However, when we come to terms with system performance or maintainability reasons, the above will fail.

The log message will print to the console and it will always do so where the code is being executed unless you wrap if with a if.. else statements.

And what if you're working on a web application that has a high number of requests by the hour or seconds? Printing of such logging messages will definitely eat into the server's resources.

The printing of the log message is always to the console, how about printing it to a specific file, limited by size or date? How about getting the system automatically email you the exception stack trace whenever caught exception is encountered?

 

Why use log4j?

Undeniably there are multiple java logging frameworks available, but why log4j?

In fact Java 1.4 SDK already has a logging API which you can use for simple projects. However, for easy customization and for a full-fledged enterprise system, you might want to use a more stable implementation or one which is used by many others.

There are a lot of functionalities that you might find useful, or if you're using JDK logging API you might found that some tasks can easily be achieved using Log4j rather than coding it yourself.

Easy customization is a plus to the Log4j too. Most of the configuration can be done in the configuration file level either in a property file or XML file. A simple property file and XML file is all it takes to enable your logging.

A good article on logging framework comparison is in Wikipedia http://en.wikipedia.org/wiki/Java_Logging_Frameworks

It also summarizes and explains about the Loggers, Formatters, Appenders or Handlers.

Thus in this article, I will only cover how to integrate Log4J to your application and leave the simple decision of defining what logger levels you want, etc to yourself.

Read on for a simple example on how to integrate Log4J in your standalone java application or in your web application.

 

How to use Log4j in Java Apps

Download Log4j

Latest version for download as of now is 1.2.14. Download the required files at http://logging.apache.org/log4j/docs/download.html . Find the link for logging-log4j-1.2.14.zip if you're using Windows or the tar.gz for others.

Run a sample

To illustrate how easy the basics of Log4j can be used, I'm running the included examples from the download with NetBeans IDE 5.5. You can use your own preferred IDE as long as you're able to setup the examples and get them running.

You need to add the log4j -1.2.14.jar from the dist folder of the extracted downloaded file in to the classpath or your project library.

I ran the InitUsingLog4JProperties example which has a simple class which just prints out logging messages with a 3 liner log4j.properties.

 

Printing message

To output your messages through Log4J is as easy as 1,2,3.

1) Add import statements:

import org.apache.log4j.Logger;

2) Declare local variable in every class you are going to use the logging:

private static Logger logger = Logger.getLogger(InitUsingXMLPropertiesFile.class);

3) Print your log message(s):

logger.debug("Hello, my name is Homer Simpson.");

 

 

Customizing for your use

The original property file enables the printing out the logging messages to a swing logging console. I am not going to use it. I wonder why someone would use a swing program to view instant log messages.

Since I prefer logging of the messages to file, I have modified the log4j.properties,

Thus, the changes I have made is

1) Add a line in main method of InitUsingLog4JProperties

PropertyConfigurator.configure("<file_path>\\log4j.properties");

// Add a bunch of logging statements ...

logger.debug("Hello, my name is Homer Simpson.");

 

 

* Note that the above is not required if you do not change the filename of log4j.properties and it is in the classpath. I like to load it in the program itself so if you place it inside a specific config folder and a startup class that does all other initializations, you can include configuration of log4j inside as well.

 

2) Change log4j.properties

Sample log4j.properties

# ***** Set root logger level to WARN and its two appenders to stdout and R.

log4j.rootLogger=DEBUG, stdout, R

 

 

# ***** stdout is set to be a ConsoleAppender.

log4j.appender.stdout=org.apache.log4j.ConsoleAppender

# ***** stdout uses PatternLayout.

log4j.appender.stdout.layout=org.apache.log4j.PatternLayout

# ***** Pattern to output the caller's file name and line number.

log4j.appender.stdout.layout.ConversionPattern=%5p [%t] (%F:%L) - %m%n

 

# ***** R is set to be a RollingFileAppender.

log4j.appender.R=org.apache.log4j.RollingFileAppender

log4j.appender.R.File=C:/log4jexample.log

# ***** Max file size is set to 100KB

log4j.appender.R.MaxFileSize=100KB

# ***** Keep one backup file

log4j.appender.R.MaxBackupIndex=1

# ***** R uses PatternLayout.

log4j.appender.R.layout=org.apache.log4j.PatternLayout

log4j.appender.R.layout.ConversionPattern=[%5p] %d{mm:ss} (%c:%L) - %m%n

 

log4j.rootLogger=DEBUG, stdout, R

signifies that the default logger level is DEBUG <refer other levels at http://logging.apache.org/log4j/docs/api/org/apache/log4j/Level.html > at it prints to the console and “R” appender

Hence, we will have stdout appender settings and R appender settings.

 

log4j.appender.stdout

This setting in the property file defines that it will print to console with the pattern specified. For conversion pattern reference, please refer to: http://logging.apache.org/log4j/docs/api/org/apache/log4j/PatternLayout.html

 

 

log4j.appender.R

This setting in the property file defines that R appender will print logging messages as RollingFile and the file located at C:/log4jexample.log with the max size of 100KB.

 

The content of the log file after run

[DEBUG] 35:42 (examples.lf5.InitUsingLog4JProperties.InitUsingLog4JProperties:78) - Hello, my name is Homer Simpson.

[DEBUG] 35:42 (examples.lf5.InitUsingLog4JProperties.InitUsingLog4JProperties:79) - Hello, my name is Lisa Simpson.

 

 

 

Properties, XML

The above configuration is in properties file. If you prefer to use XML, see InitUsingXMLPropertiesFile

The only difference is loading of the configuration using DOMConfigurator instead of PropertyConfigurator.

 

By resource path:

String resource =

"/examples/lf5/InitUsingXMLPropertiesFile/example.xml";

URL configFileResource =

InitUsingXMLPropertiesFile.class.getResource(resource);

DOMConfigurator.configure(configFileResource.getFile());

 

 

 

By file path:

DOMConfigurator.configure("<file_path>\\log4j.xml");

 

To obtain the same result of using properties file, XML below is used:

 

<?xml version="1.0" encoding="UTF-8"?>

<!DOCTYPE log4j:configuration SYSTEM "log4j.dtd">

 

<log4j:configuration>

<appender name="consoleAppender" class="org.apache.log4j.ConsoleAppender">

<param name="Target" value="System.out"/>

<layout class="org.apache.log4j.PatternLayout">

<param name="ConversionPattern" value="%5p [%t] (%F:%L) - %m%n"/>

</layout>

</appender>

<appender name="rollingFileAppender" class="org.apache.log4j.RollingFileAppender">

<param name="File" value="C:/log4jexample.log"/>

<param name="Append" value="true"/>

<param name="MaxFileSize" value="100KB"/>

<param name="MaxBackupIndex" value="1"/>

<layout class="org.apache.log4j.PatternLayout">

<param name="ConversionPattern" value="[%5p] %d{mm:ss} (%c:%L) - %m%n"/>

</layout>

</appender>

<category name="examples" additivity="false">

<priority value ="debug"/>

<appender-ref ref="rollingFileAppender"/>

</category>

<root>

<priority value ="debug"/>

<appender-ref ref="consoleAppender"/>

</root>

</log4j:configuration>

 

 

Another point to note is that besides using properties file and XML, you can configure log4j via code as well. Once again, why should you walk if you can fly?

 

 

How to use Log4j in Web Applications

 

Basically the configuration and logging are the same as what you have to do on a typical java application with Log4j.

The only difference will be where the initialization process, you can use a startup servlet to initialize the Log4j configuration.

Put the log4j library jar file into WEB-INF\lib folder too.

 

Below is a sample of the servlet:

 

import javax.servlet.ServletException;

import javax.servlet.http.HttpServlet;

 

public class Log4jStartupServlet extends HttpServlet {

public void destroy() {

thread.interrupt();

super.destroy();

}

 

public void init() throws ServletException {

super.init();

//Using XML, replace this with PropertyConfigurator if using properties file

DOMConfigurator.configure("<file_path>\\log4j.xml");

}

 

}

 

 

And web.xml:

 

<?xml version="1.0" encoding="UTF-8"?>

<web-app version="2.4"

xmlns="http://java.sun.com/xml/ns/j2ee"

xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"

xsi:schemaLocation="http://java.sun.com/xml/ns/j2ee

http://java.sun.com/xml/ns/j2ee/web-app_2_4.xsd">

<servlet>

<servlet-name>log4jStartup</servlet-name>

<servlet-class>Log4jStartupServlet</servlet-class>

<load-on-startup>2</load-on-startup>

</servlet>

</web-app>

 

Notes

More often than not, problem that you most probably will encounter is the following:

 

log4j:WARN No appenders could be found for logger (org.apache.commons.digester.Digester).

log4j:WARN Please initialize the log4j system properly.

 

If the above happens, it is because log4j configuration has not been loaded. Double check the path or the content of your log4j.properties or log4j.xml.

 

References

http://logging.apache.org/index.html

http://en.wikipedia.org/wiki/Log4j

http://java.sun.com/j2se/1.4.2/docs/guide/lang/index.html

http://en.wikipedia.org/wiki/Apache_License

http://www.javaworld.com/javaforums/showflat.php?Cat=2&Board=TheoryPractice&Number=2396&page=0&view=collapsed&sb=11&o=&fpart=1

 

3 Comments »

RSS feed for comments on this post. TrackBack URI

  1. [...] you noticed my previous blogs, Log4j source codes are a plain text with no highlighting of reserved words or like the way it is shown in [...]

  2. [...] read more | digg story [...]

  3. Thanks… it has helped a lot. I have provided a link to this entry from my blog.


Leave a comment

XHTML: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <pre> <del datetime=""> <em> <i> <q cite=""> <strike> <strong>

Blog at WordPress.com. | Theme: Pool by Borja Fernandez.
Entries and comments feeds.