Log4j Study

 

1. Log4j logs java application errors. The error can be printed out on console or files.

You only need download log4j jar file and put at your application root folder to use it. Current version log4j-1.2.8.jar

 

2. Sample code

  • Listing 1. Setup and configuring log4j in programmatically.
  • Listing 2. User external property file to set up the configuration parameters.
Listing 1: Setup and configuring log4j programmatically
/*
 *
 * To log an application class, follow these steps:
 * 1. Import log4j package in the class. (log4j-1.2-8.jar)
 * 2. Inside the class, instantiate a logger object using Logger.getLogger( ) static method. 
 * 3. Instantiate layouts (readymade or user-defined) to be assigned to appenders. 
 * 4. Instantiate appenders and assign desired layout to them by passing the layout object as parameter to their constructors. 
 * 5. Assign the instantiate appenders to the Logger object by invoking its addAppender( ) method with desired appender as parameter. 
 * 6. Invoke appropriate printing methods on Logger object to perform logging. 
 * This code setup all parameters programmatically. It is beter to use outside configuration
 * file. Steps 3, 4, and 5 can be skipped in case of external configuration.
 * Reference Source: 
 * http://www.developer.com/open/article.php/10930_3097221_1
 */

/*Import necessary log4j API classes*/
import org.apache.log4j.*;

public class CodeAlong {
	static Logger myLogger = Logger.getLogger(CodeAlong.class.getName());
	Appender myAppender;
	SimpleLayout myLayout;
	
	//constructor
	public CodeAlong()
	{ 
		// Set logger priority level programmatically. 
		myLogger.setLevel(Level.INFO);
		// Instantiate a layout and an appender, assign layout to appender programmatically 
		myLayout = new SimpleLayout();
		myAppender = new ConsoleAppender(myLayout);    
		
		// Assign appender to the logger programmatically 
		myLogger.addAppender(myAppender);
	} 
	//end constructor	
	
	public static void main(String[] args) {
		System.out.println("Hello from "+ CodeAlong.class.getName());
		CodeAlong myCode =new CodeAlong();
		myCode.do_something(5, 1.2f);
	}

	public void do_something( int a, float b)
	{
		// This log request enabled and log statement logged, since INFO = INFO 
		myLogger.info("The values of parameters passed to method do_something are: " + a + ", " + b); 
		// this log request is not enabled, since DEBUG < INFO
		myLogger.debug("Operation performed successfully");
		Object x=null;
		if (x == null){
			// this log request is enabled and log statement logged, since ERROR > INFO
			myLogger.error("Value of X is null");
		}
	} //end do_something()
}

/*** print on console is:
Hello from CodeAlong
INFO - The values of parameters passed to method do_something are: 5, 1.2
ERROR - Value of X is null
****/

Listing 2: Use external property file to setup log4j parameters.
/*
 * Created on Sep 6, 2005
 *
 * To log an application class, follow these steps:
 * 1. Import log4j package in the class. (log4j-1.2-8.jar)
 * 2. Inside the class, instantiate a logger object using Logger.getLogger( ) static method. 
 * 3. load property file 
 * 4. Invoke appropriate printing methods on Logger object to perform logging. 
  */

/*Import necessary log4j API classes*/
import org.apache.log4j.*;
import org.apache.log4j.PropertyConfigurator;

public class useProperty {
	static Logger myLogger = Logger.getLogger(useProperty.class.getName());
	Appender myAppender;
	SimpleLayout myLayout;
	
	//constructor
	public useProperty()
	{ 
		// Invoke external property file.
		//PropertyConfigurator.configure("simple.properties");
		PropertyConfigurator.configure("simple2.properties");
		
		// Assign appender to the logger programmatically 
		myLogger.addAppender(myAppender);
	} //end constructor	
	
	public static void main(String[] args) {
		System.out.println("Hello from "+ useProperty.class.getName());
		useProperty myCode =new useProperty();
		myCode.do_something(5, 1.2f);
	}

	public void do_something( int a, float b)
	{
		// This log request enabled and log statement logged, since INFO = INFO 
		myLogger.info("The values of parameters passed to method do_something are: " + a + ", " + b); 
		// this log request is not enabled, since DEBUG < INFO
		myLogger.debug("Operation performed successfully");
		Object x=null;
		if (x == null){
			// this log request is enabled and log statement logged, since ERROR > INFO
			myLogger.error("Value of X is null");
		}
	} //end do_something()
}

/*** print on console and log file is:
Hello from useProperty
 INFO [main] (useProperty.java:45) - The values of parameters passed to method do_something are: 5, 1.2
DEBUG [main] (useProperty.java:47) - Operation performed successfully
ERROR [main] (useProperty.java:51) - Value of X is null
****/

Two sample property files, sample.properies and samples.properies 

#sample.properies
# Set root logger level to INFO and its only appender to A1.
log4j.rootLogger=INFO, A1

# A1 is set to be a ConsoleAppender.
log4j.appender.A1=org.apache.log4j.ConsoleAppender

# A1 uses PatternLayout.
log4j.appender.A1.layout=org.apache.log4j.PatternLayout
log4j.appender.A1.layout.ConversionPattern=%-4r [%t] %-5p %c %x - %m%n

 

#sample2.properties
# Set root logger level to DEBUG and appender to stdout and R.
log4j.rootLogger=debug, 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

#save log to file example.log
log4j.appender.R=org.apache.log4j.RollingFileAppender
log4j.appender.R.File=example.log

log4j.appender.R.MaxFileSize=100KB
# Keep one backup file
log4j.appender.R.MaxBackupIndex=1

log4j.appender.R.layout=org.apache.log4j.PatternLayout
log4j.appender.R.layout.ConversionPattern=%p %t %c - %m%n
 

Reference Articles

Simple and easy:
http://www.developer.com/open/article.php/10930_3097221_1

Complete:
http://logging.apache.org/log4j/docs/manual.html

local copy