Pages Navigation Menu

Coding is much easier than you think

Struts 2 + Log4j integration example

Struts 2 + Log4j integration example

 
In this tutorial we will learn about integrate Log4j with Struts 2 framework.
 

 

Log4j Appender

 
Create a text file named “log4j.properties“, put it at the root of the project classpath. The log4j.properties or appender file is the Log4j configuration file, it defines how the Log4j logging mechanism work.
 
** UPDATE: Struts 2 Complete tutorial now available here.
 
In this example, it will log all the logging detail and outputs it to an external file “C:\\loggerfile.txt“.

log4j.properties
 

# Direct log messages to a log file
log4j.appender.file=org.apache.log4j.RollingFileAppender
log4j.appender.file.File=C:\\loggerfile.txt
log4j.appender.file.MaxFileSize=10MB

log4j.appender.file.layout=org.apache.log4j.PatternLayout
log4j.appender.file.layout.ConversionPattern=%d{ABSOLUTE} %5p %c{1}:%L - %m%n
 
# 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

# Root logger option
log4j.rootLogger=warn, file, stdout

 

Action Class

 
To use Log4j in Struts 2 framework, you can get the Log4j logger via Logger.getLogger() and log it directly.

package com.simplecode.action;

import org.apache.log4j.Logger;
import com.opensymphony.xwork2.ActionSupport;

public class LoggerAction extends ActionSupport {

	private static final long serialVersionUID = 1L;
	private static final Logger logger = Logger.getLogger(LoggerAction.class);

	public String execute() throws Exception {
		logger.warn("Warning .......");
		logger.error("Error .......");
		return SUCCESS;
	}
}

 

Demo

 
Now, all the logging details will be logged into the file, named “C:\\loggerfile.txt“. See sample :

23:37:38,165 WARN LoggerAction:14 – Warning …….
23:37:38,166 ERROR LoggerAction:15 – Error …….

 

Reference

  1. Log4j official website
  2. Struts 2 exceptions and logging

 

About Mohaideen Jamil