Thursday, April 16, 2009

Adding logging in Java Applications using LOG4J

Step1: Create Log4J Properties File





# this logger is for application logging

log4j.rootLogger=INFO, STDOUT



# *****************************************************************

# Appender A1 - Rolling File

# *****************************************************************

# Define the actual Appender to use that is associated with our string; in this

# case we select the RollingFileAppender which writes to a file

log4j.appender.STDOUT=org.apache.log4j.RollingFileAppender


# Set properties for the RollingFileAppender

log4j.appender.STDOUT.File=.../log/Application.log


# Set the layout for the Appender

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

log4j.appender.STDOUT.layout.ConversionPattern=%d %-5p -[%c] %m%n


# Set max size (25 MB each file) and backup index (save 4000 files) that's 100GB!

log4j.appender.STDOUT.MaxFileSize=15MB

log4j.appender.STDOUT.MaxBackupIndex=10





Step2: PropertyConfigurator



This line in your startup java class(Main method).


PropertyConfigurator.configure(".../log/Application.log");



Step3: Declar a static variable



Declar a static variable for the class will use the log


private static final Logger LOG = Logger.getLogger(Sample.class);




Step4: write a log in your program



LOG.debug("");


or


LOG.error("");


or


LOG.warn("");


or

LOG.info("");




Step5: import Jar file for LOG4J



log4j-1.2.14.jar






LOG4J example in Java Application:



1.log4j.prperties (Use above Properties File in step1)



2.Sample.java



import org.apache.log4j.Logger;

import org.apache.log4j.PropertyConfigurator;

public class Sample

{

private static final Logger LOG = Logger.getLogger(Sample.class);


public void display(){

LOG.info("Display method");

}


public static void main(String[] args)

{

PropertyConfigurator.configureAndWatch(".../src/log4j.properties",5000);

System.out.println("Hello World!");

Sample sample = new Sample();

sample.display();

}

}


3.Download jar file (log4j-1.2.14.jar)then add it.



4.Run your application.

Post a Comment

  © Blogger templates Newspaper III by Ourblogtemplates.com 2008

Back to TOP