MrBool
You must be logged in to give feedback. Click here to login
[Close]

You must be logged to download.

Click here to login

[Close]

MrBool is totally free and you can help us to help the Developers Community around the world

Yes, I'd like to help the MrBool and the Developers Community before download

No, I'd like to download without make the donation

[Close]

MrBool is totally free and you can help us to help the Developers Community around the world

Yes, I'd like to help the MrBool and the Developers Community before download

No, I'd like to download without make the donation

Log4j - An open source Java logging framework

This article describes the log4j. Log4j is an open source logging framework with fully configurable external configuration files.It allows the developer to control log statements based on application requirement.

[close]

You didn't like the quality of this content?

Would you like to comment what you didn't like?

Introduction

The log4j is a java based message logging utility from Apache Software Foundation. It is a reliable, fast and flexible logging framework which allows the developers to put logging messages in their applications. These logging messages are helpful to debug the application and also to understand the flow.

Components

The log4j has three major components:

  • loggers - These captures the information which is to be logged out.
  • appenders - These publish the logged information to the desired outputs.
  • layouts - These formats the logging information in different styles.

Features

The log4j has the following features:

  • It is thread safe
  • It is speed optimized
  • It has a named logger hierarchy
  • Supports multiple appenders per logger
  • Supports internationalization
  • Logging behavior can be set at runtime via configuration file
  • Uses multilevels:
    1. ALL
    2. TRACE
    3. DEBUG
    4. INFO
    5. WARN
    6. ERROR
    7. FATAL
  • Output format can be easily changed

Installation

The log4j is a complete open source utility. It is distributed as a binary jar file from Apache and is certified by the open source initiative. The latest source code and binary file can be downloaded from http://logging.apache.org/log4j/. The downloaded file comes in the format - apache-log4j-x.x.x.tar.gz (unix format). Once downloaded, the following steps are required:

Step 1 - Unzip & untar the downloaded file

Step 2 - Set the path & classpath variables as under

$ export CLASSPATH=       $CLASSPATH:/usr/local/apache-log4j-1.2.15/log4j-1.2.15.jar
$ export PATH=$PATH:/usr/local/apache-log4j-1.2.15/

Same steps needs to be followed for windows and other operating systems.

Configuration

The log4j can be configured in three ways:

  • Using properties file
  • Using XML file
  • Through Java code

Configuration via these files has an advantage as we can turn on or off the logging without touching the actual source code of the application. In case there is an issue with the application a developer can simply turn on the logging by changing some parameters and the turn it back off when the issue is resolved.

Listing 1: A sample log4j.properties file

log4j.rootLogger = ERROR, stdout, R
log4j.appender.stdout = org.apache.log4j.ConsoleAppender
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
log4j.appender.R = org.apache.log4j.RollingFileAppender
# setting the logging file (put absolute path if needed)
log4j.appender.R.File = application.log
log4j.appender.R.MaxFileSize = 5000KB
# Keep one backup file
log4j.appender.R.MaxBackupIndex = 2
log4j.appender.R.layout = org.apache.log4j.PatternLayout
log4j.appender.R.layout.ConversionPattern = %d %p %t [%F:%L] - %m%n
log4j.logger.com.applicaiton.package = DEBUG
log4j.appender.R.layout.ConversionPattern = %p %t %c - %m%n

Listing 2: A Sample log4j.xml file

<?xml version = "1.0" encoding = "UTF-8"?>
<!DOCTYPE log4j:configuration PUBLIC "-//LOGGER" "http://logging.apache.org/log4j/1.2/apidocs/org/apache/log4j/xml/doc-files/log4j.dtd">
<log4j:configuration>
    <!-- 
         an appender is an output destination, such as the console or a file; names of appenders are arbitrarily chosen
    -->
    <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>
 
    <!-- 
         loggers of category 'org.springframework' will only log messages of level "info" or higher;
         if you retrieve Loggers by using the class name (e.g. Logger.getLogger(AClass.class))
         and if AClass is part of the org.springframework package, it will belong to this category
    -->
    <logger name = "com.application">
        <level value = "info"/>
    </logger>
 
    <!-- 
         everything of spring was set to "info" but for class 
         PropertyEditorRegistrySupport we want "debug" logging 
    -->
    <logger name = " com.application ">
        <level value = "debug"/>
    </logger>
 
    <logger name = " com.application ">
        <level value = "info"/>
    </logger>
  
    <root>
        <!-- 
            all log messages of level "debug" or higher will be logged, unless defined otherwise 
            all log messages will be logged to the appender "stdout", unless defined otherwise 
        -->
        <level value = "debug" />
        <appender-ref ref = "stdout" />
    </root>
</log4j:configuration>

Listing 3: A Sample java code snippet used for log4j configuration

//create the appender
ConsoleAppender consoleAppender = new ConsoleAppender();  
//configure the appender
String PATTERN = "%d [%p|%c|%C{1}] %m%n";
consoleAppender.setLayout(new PatternLayout(PATTERN)); 
consoleAppender.setThreshold(Level.FATAL);
consoleAppender.activateOptions();
//add appender to any Logger (here is root)
Logger.getRootLogger().addAppender(consoleAppender);
FileAppender fAppender = new FileAppender();
fAppender.setName("FileLogger");
fAppender.setFile("mylog.log");
fAppender.setLayout(new PatternLayout("%d %-5p [%c{1}] %m%n"));
fAppender.setThreshold(Level.DEBUG);
fAppender.setAppend(true);
fAppender.activateOptions();
  /add appender to any Logger (here is root)
  Logger.getRootLogger().addAppender(fAppender)
  //repeat with all other desired appenders

Logging levels

The log4j has different levels using which messages are logged into the output file. These levels are defined as under:

Different log4j levels table

Figure 1: Different log4j levels table

Implementation

Below we can see a sample log4j implementation is listed under.

Listing 4: Sample log4j implementation class

import org.apache.log4j.Logger;

public class MyLogginTestClass {

private static org.apache.log4j.Logger log = Logger
.getLogger(MyLogginTestClass.class);
public static void main(String[] args) {
log.trace(" This is a sample Trace Message! ");
log.debug(" This is a sample Debug Message! ");
log.info(" This is a sample Info Message! ");
log.warn(" This is a sample Warn Message! ");
log.error(" This is a sample Error Message! ");
log.fatal(" This is a sample Fatal Message! ");
}
}

Once compiled and executed, this program yields the following output.

Listing 5: Sample program output

This is a sample Debug Message!
This is a sample Info Message!
This is a sample Warn Message!
This is a sample Error Message!
This is a sample Fatal Message!

Formatting

log4j provides different layout objects, each of these can format logging data as per the layouts. Customized layout objects can also be created which can format the logging data in a specified manner. The log4j provides the following layout types:

  • DateLayout
  • HTMLLayout
  • PatternLayout
  • SimpleLayout
  • XMLLayout

Sample Program

Lets define the log4j.properties file as under:

Listing 6: Sample log4j.properties file

# Define the root logger with appender file
log = /usr/home/log4j
log4j.rootLogger = DEBUG, FILE
# Define the file appender
log4j.appender.FILE = org.apache.log4j.FileAppender
log4j.appender.FILE.File = ${log}/application.log
# Define the layout for file appender
log4j.appender.FILE.layout = org.apache.log4j.PatternLayout
log4j.appender.FILE.layout.conversionPattern = %m%n

Listing 7: Sample Java code using this properties file.

import org.apache.log4j.Logger;
import java.io.*;
import java.sql.SQLException;
import java.util.*;

public class log4jTestExample{

/* Get actual class name to be printed on */
static Logger log = Logger.getLogger(
log4jTestExample.class.getName());
public static void main(String[] args) throws IOException, 
SQLException{
log.debug("Hello all ! This is a debug message from log4jTestExample ");
log.info("Hello all ! This is an info message from log4jTestExample ");
}
}

Steps to execute this program

  • Create log4j.properties as shown above.
  • Create log4jTestExample.java as shown above and compile it using javac log4jTestExample.java.
  • Execute log4jTestExample binary to run the program using java log4jTestExample.

Preconditions to execute this program

All the relevant libraries should be in the CLASSPATH and the log4j.properties should be in the PATH. Once compiled and executed, the following messages should go in the /usr/home/log4j/application.log file

Listing 8: Sample message in the log file

Hello all ! This is a debug message from log4jTestExample
Hello all ! This is an info message from log4jTestExample

Conclusion

To conclude with, we can say that Log4j is a standard Java library that specializes on logging framework. It has different logging levels which can be set depending upon the application requirement.

As a standard practice Log4j is configured using standard configuration file. Following are some important points to remember.

  • log4j is a java based open source logging utility used in Java applications
  • log4j has three components - loggers, appenders & layouts
  • log4j has different log levels
  • The latest source code and binary file can be downloaded from http://logging.apache.org/log4j/
  • Log outputs can be formatted in different formats


Website: www.techalpine.com Have 16 years of experience as a technical architect and software consultant in enterprise application and product development. Have interest in new technology and innovation area along with technical...

What did you think of this post?
Services
Know how to keep MrBool Online
SUPPORT US
SUPPORT US
With your help, we can keep providing free content and helping you to be a better professional
support us
[Close]
To have full access to this post (or download the associated files) you must have MrBool Credits.

  See the prices for this post in Mr.Bool Credits System below:

Individually � in this case the price for this post is US$ 0,00 (Buy it now)
in this case you will buy only this video by paying the full price with no discount.

Package of 10 credits - in this case the price for this post is US$ 0,00
This subscription is ideal if you want to download few videos. In this plan you will receive a discount of 50% in each video. Subscribe for this package!

Package of 50 credits � in this case the price for this post is US$ 0,00
This subscription is ideal if you want to download several videos. In this plan you will receive a discount of 83% in each video. Subscribe for this package!


> More info about MrBool Credits
[Close]
You must be logged to download.

Click here to login