Spring项目中怎么配置log4j

在spring项目中配置log4j

http://blogger.org.cn/blog/more.asp?name=lhwork&id=17174

其实我们只要查看spring的sample示例就知道怎么做。

首先创建好集成了spring的web项目。

下面配置:

一、在web.xml中加入下面内容

<context-param>
		<param-name>webAppRootKey</param-name>
		<param-value>SpringStrutsHibernate.root</param-value>
	</context-param>
	<context-param>
		<param-name>log4jConfigLocation</param-name>
		<param-value>/WEB-INF/log4j.properties</param-value>
	</context-param>
	<listener>
		<listener-class>org.springframework.web.util.Log4jConfigListener</listener-class>
	</listener>

 

二、加入log4j.jar到WEB-INF/lib下。

三、拷贝log4j.properties到WEB-INF下面。

# For JBoss: Avoid to setup Log4J outside $JBOSS_HOME/server/default/deploy/log4j.xml!
# For all other servers: Comment out the Log4J listener in web.xml to activate Log4J.
log4j.rootLogger=INFO, stdout, logfile

log4j.appender.stdout=org.apache.log4j.ConsoleAppender
log4j.appender.stdout.layout=org.apache.log4j.PatternLayout
log4j.appender.stdout.layout.ConversionPattern=%d %p [%c] - %m%n

log4j.appender.logfile=org.apache.log4j.RollingFileAppender
log4j.appender.logfile.File=${SpringStrutsHibernate.root}/WEB-INF/log/log4j.log
log4j.appender.logfile.MaxFileSize=512KB
# Keep three backup files.
log4j.appender.logfile.MaxBackupIndex=3
# Pattern to output: date priority [category] - message
log4j.appender.logfile.layout=org.apache.log4j.PatternLayout
log4j.appender.logfile.layout.ConversionPattern=%d %p [%c] - %m%n

 

里面使用的SpringStrutsHibernate.root,系统会默认取到SpringStrutsHibernate项目的根目录。

把项目部署在tomcat下。运行就会在SpringStrutsHibernate/WEB-INF/log文件夹下产生一个log4j.log文件里面记录了日志信息。

 

在附件的项目中集成了spring+struts

在LoginAction中打印出来日志信息

package com.lwf.spring.web.action;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.log4j.Logger;
import org.apache.struts.action.Action;
import org.apache.struts.action.ActionForm;
import org.apache.struts.action.ActionForward;
import org.apache.struts.action.ActionMapping;

import com.lwf.spring.web.dao.UserDao;
import com.lwf.spring.web.form.LoginForm;

public class LoginAction extends Action {

	 static Logger logger = Logger.getLogger(LoginAction.class);   
	private UserDao userDao;
	public ActionForward execute(ActionMapping mapping, ActionForm form,
			HttpServletRequest request, HttpServletResponse response)
			throws Exception {
		
		LoginForm loginForm = (LoginForm)form;
		String name = loginForm.getName();
		String pwd = loginForm.getPassword();
		
		userDao.add(name, pwd);
		logger.info("just test logger");
		logger.debug("debug log message");
		return mapping.findForward("success");
	}
	
	
	public void setUserDao(UserDao userDao) {
		this.userDao = userDao;
	}

}

 

你可能感兴趣的:(apache,spring,log4j,Web,struts)