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:
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.
Nam Ha Minh is certified Java programmer (SCJP and SCWCD). He began programming with Java back in the days of Java 1.4 and has been passionate about it ever since. You can connect with him on Facebook and watch his Java videos on YouTube.
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?
Is there a specific configuration for struts2 app deployed in a tomcat server? The example doesn’t seem to work for my application. It doesn’t log anything whether on a log file nor the console. No log file is even created. Thanks in advance.
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.