Friday, January 7, 2011

Log4j Implmentation with an example.

Article discusses the following
-------------------------------------------------


What is Log4j.
Example Implementation 
About Log level , appender, Layout in Log4j

Log4j is an OpenSource logging API developed under the Jakarta Apache project.Log4j allows developers to insert log statements in their code and configure them externally.

Logically, log4j can be viewed as being comprised of three main components: logger, appender, and layout namely. The functionalities of each of these components are accessible through Java classes of the same name. Users can extend these basic classes to create their own loggers, appenders, and layouts. 

You can download the current version of log4j from the project home page.
http://logging.apache.org/log4j/

Log4j can be configured with two ways : log4j.properties(tradtional way)  , Log4j.xml( More and more applications are adopting to this now).

Log4j.properties example
-------------------------
--------

  • Create a Java project.
  • Add the log4j.jar to the build path of the project.
  • Create a file named log4j.properties in the src folder with the following content.
          ### direct log messages to 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{ABSOLUTE} %5p %c{1}:%L - %m%n
        log4j.rootLogger=debug, stdout

------  click below to read More ( no need to click in case of a full page view) ---



Create a class with the following content:

package somepackage.logexample;
import org.apache.log4j.Logger;

public class LogClass {
    private static org.apache.log4j.Logger log = Logger
        .getLogger(LogClass.class);

    public static void main(String[] args) {

            log.trace("Trace");
            log.debug("Debug");
            log.info("Info");
            log.warn("Warn");
            log.error("Error");
            log.fatal("Fatal");

    }
}


Run it.
Change the line
log4j.rootLogger=debug, stdout
to
log4j.rootLogger=warn, stdout
and run your java application again.

Log4j.xml example
------------------
------


Create a file named log4j.xml with the following content in your src folder:
<?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>
Copy the log4j.dtd into the source folder as well. You can find it in the download of log4j.
The XML requires a dom4j.jar which is available default after java 1.5

Run the example again.

Log Levels
-----------------
The log levels are Trace, Debug, warn, Info, fatal ( These levels by name itself
are self-explanatory about what kind of Information to be logged.)
you can also set your cusotm levels.

Layout of the log file ( how the log message looks like)
-------------------------------------------------------
------------------

First you define the layout.

log4j.appender.stdout.layout=org.apache.log4j.PatternLayout
The pattern layout requires another parameter, i.e. the pattern.
log4j.appender.stdout.layout.ConversionPattern=%d{ABSOLUTE} %5p %c{1}:%L - %m%n
The best up-to-date documentation about available layouts can be found in the API
documentation: http://logging.apache.org/log4j/docs/api/org/apache/log4j/Layout.html
There you can see that we have DateLayout, HTMLLayout, PatternLayout, SimpleLayout,
XMLLayout as options.
SimpleLayout has no properties to be set. It is simple.

Types of log appender ( where to write the log message to? like a file or console etc.,)
-------------------------------------------------------------------------------------------------
An appender specifies where your log messages are written to.
There is a wide choice of appenders available.
All appenders are direct or indirect subclasses of the AppenderSkeleton.
Therefore we can find all options on the following API page:
http://logging.apache.org/log4j/docs/api/org/apache/log4j/AppenderSkeleton.html
The console and the file appender are a subclass of WriterAppender.

In the next article , I will give you an update on best practices on Logging Exceptions.

No comments:

Post a Comment

subversion video