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 ““, put it at the root of the project classpath. The 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“.

# Direct log messages to a log file

log4j.appender.file.layout.ConversionPattern=%d{ABSOLUTE} %5p %c{1}:%L - %m%n
# Direct log messages to stdout
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;



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 …….



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


About Mohaideen Jamil

I'm a Full stack developer of IT exp in J2EE, AngularJs, MicroServices, Docker, Spring (Boot, MVC, Cloud), Bluemix, DevOps. Follow me on Facebook or Google Plus. If you like my tutorials, consider making a donation to this charity, thanks.

%d bloggers like this: