Friday, January 18, 2008

Using Loggers in Java Applications

In order to add logging features to your applications, you can use apache log4j API

You need 3 things

1) have access to log4j jar file

2) have a properties file that will act as a configuration environment for the logging process

3) write the appropriate Java code

here is more details using the Oracle Jdeveloper IDE

Download log4j1.3.jar from http://logging.apache.org

Put the log4j.jar in the classpath, or add it to the Jdeveloper project as shown

You need to specify where the properties file is located, otherwise logging will fail

As an example, I have create a properties file and called it log4j.properties and added placed the file at C:\

You can use the project properties dialogue to define the location of the Properties file

Invoke project properties à Run/Debug à Edit the default setting à and add the Java option shown below

-Dlog4j.configuration = file:c:/log.properties

The following is a sample properties file in which the logging output is specified (log4j.appender.R.File=C:\x.log)

Log.properties

log4j.rootLogger=INFO, R

# first appender writes to a file

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

#RollingFileAppender OPTIONS

log4j.appender.R.Threshold=INFO

log4j.appender.R.ImmediateFlush=true

log4j.appender.R.File=C:\x.log

log4j.appender.R.MaxFileSize=6000KB

log4j.appender.R.MaxBackupIndex=2

#log4j.debug=true

#log4j.disable=fatal

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

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

log4j.appender.R.layout.ConversionPattern=%p %c %d{dd/MM/yyyy HH:mm:ss} - %m%n

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

#log4j.appender.R.layout.ConversionPattern=%p %t %c - %m%n

Finally, this is an example code

package model;

import org.apache.log4j.Logger;

public class Class1 {

public Class1() {

Logger log = Logger.getLogger(Class1.class.getName());

log.warn("hello warning");

}

public static void main(String[] args) {

Class1 class1 = new Class1();

}

}

Note: the (Class1.class.getName()) retrieves the name of the current class that is being executes. Every logging message entry will have this variable printed so that the users can know which class was responsible for this entry.. off course, if you choose to use a string value instead, that strng value shall appear in each logging entry.

Thanks to Mr. Ammar for this Article..

1 comment:

Jack said...

I am bit confused in logging output shared by you. It is confusing me. Can you please provide more details regarding it. I am positively waiting for your reply.
sap project

Some/All/Major of the blog content is not mine and i'm not the writer of it, all rights reserved to the authors.