How to use log4j in Struts
- 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:
- Introduction to Struts 2 framework
- Struts beginner tutorial (Eclipse + Tomcat + XML)
- Struts Beginner Tutorial with Annotations
- Struts beginner tutorial with Convention Plugin (zero-configuration)
- How to handle exceptions in Struts
- Send e-mail with attachments in Struts
- Struts File Upload Tutorial
- Struts - Spring - Hibernate Integration Tutorial
Comments
I'm struggling in migrating the below syntax to log4j 2
log4j.logger.com.opensymphony.xwork2.interceptor=error
log4j.logger.com.opensymphony.xwork2.ognl=error
log4j.logger.com.opensymphony.xwork2.util.OgnlUtil=error
log4j.logger.com.opensymphony.xwork2.ognl.OgnlValueStack=error
No, there isn't any specific configuration for Tomcat. For the sample application, you must invoke the Struts action by typing the URL (localhost:8080/Log4jStruts2/test). Did you do that?
Thanks in advance.