1. 首先建一个初始Log4Init类
其中需入导入包: log4j-1.2.8.jar, tomcat/bin目录下的servlet-api.jar
Log4Init.java
import javax.servlet.ServletConfig; import javax.servlet.ServletException; import javax.servlet.http.HttpServlet; import org.apache.log4j.Logger; import org.apache.log4j.PropertyConfigurator; public class Log4Init extends HttpServlet { private static final long serialVersionUID = 7788159703223986067L; static Logger log = Logger.getLogger(Log4Init.class); public void init() throws ServletException{ ServletConfig config = getServletConfig(); String path = config.getServletContext().getRealPath("/"); PropertyConfigurator.configure(path + "WEB-INF/classes/log4j.properties"); log.info(" 初始化---------Log4J------"); } }
2. 然后在web.xml 配置初始化
web.xml
<!-- Log4Init -->
<servlet>
<servlet-name>log</servlet-name>
<servlet-class>cn.ssh.struts.select.Log4Init</servlet-class>
<load-on-startup>1</load-on-startup>
</servlet>
3. 增加配置文件.
log4j.properties
# This is the configuring for logging displayed in the Application Server
log4j.rootCategory=INFO,stdout,logfile
#stdout configure
log4j.appender.stdout = org.apache.log4j.ConsoleAppender
log4j.appender.stdout.layout=org.apache.log4j.PatternLayout
log4j.appender.stdout.layout.ConversionPattern= %d %p [%c] %L - <%m>%n
#logfile configure
log4j.appender.logfile=org.apache.log4j.DailyRollingFileAppender
#log4j.appender.logfile.DatePattern=.yyyy-MM-dd-HH-mm'.log'
#log4j.appender.logfile.File=${catalina.base}/logs/smartcom.log
log4j.appender.logfile.File=${catalina.base}/logs/ssh_xml.log
log4j.appender.logfile.DatePattern='_'yyyy-MM-dd-HH-mm'.log'
log4j.appender.logfile.layout=org.apache.log4j.PatternLayout
#log4j.appender.logfile.layout.ConversionPattern=%d %p [%c] - <%m>%n
log4j.appender.logfile.layout.ConversionPattern=%-d{yyyy-MM-dd HH\:mm\:ss} [%c]-[%p] %m%n