- Details
- Written by Nam Ha Minh
- Last Updated on 31 July 2019   |   Print Email
To use log4j in a Struts application, simply put log4j configuration file (
log4j.propertiesor
log4j.xml) under the root of the classpath. For a Struts web application, it would be under
WEB-INF\classes directory. When developing a Struts project in Eclipse, you can put the file under
src directory (and Eclipse will automatically put it into classpath), as shown in the following screenshot:
Here’s a sample
log4j.properties file:
# LOG4J configuration
log4j.rootLogger=INFO, Appender1, Appender2
log4j.appender.Appender1=org.apache.log4j.ConsoleAppender
log4j.appender.Appender1.layout=org.apache.log4j.PatternLayout
log4j.appender.Appender1.layout.ConversionPattern=%-7p %d [%t] %c %x - %m%n
log4j.appender.Appender2=org.apache.log4j.FileAppender
log4j.appender.Appender2.File=D:/Logs/Struts2.log
log4j.appender.Appender2.layout=org.apache.log4j.PatternLayout
log4j.appender.Appender2.layout.ConversionPattern=%-7p %d [%t] %c %x - %m%n
This log4j configuration file specifies two appenders: a
ConsoleAppender and a
FileAppender (the log file will be written to
D:/Logs/Struts2.log, so make sure the directory exists).Then we can use log4j in a Struts action class like this:
package net.codejava.struts;
import org.apache.log4j.Logger;
import com.opensymphony.xwork2.ActionSupport;
public class TestAction extends ActionSupport {
static final Logger LOGGER = Logger.getLogger(TestAction.class);
public String execute() {
LOGGER.info("This is a debug log message from Struts2");
return SUCCESS;
}
}
Output in the server’s console when running this action (
http://localhost:8080/Log4jStruts2/test):
And notice the log is also written to the file
D:/Logs/Struts2.log.
Related Java Logging Tutorials:
Other Struts Tutorials:
About the Author:
Nam Ha Minh is certified Java programmer (SCJP and SCWCD). He started programming with Java in the time of Java 1.4 and has been falling in love with Java since then. Make friend with him on
Facebook and watch
his Java videos you YouTube.