关于java web项目使用log4j

pom.xml中添加依赖。

<dependency>
	<groupId>log4j</groupId>
	<artifactId>log4j</artifactId>
	<version>1.2.17</version>
</dependency>

maven会自动添加相应的jar包

配置log4j初始化用的servlet

web.xml中添加下面servlet

<servlet>
	<servlet-name>log4j-init</servlet-name>
	<servlet-class>com.suyang.servlet.Log4jInit</servlet-class>
	<init-param>
		<param-name>log4j-init-file</param-name>
		<param-value>\WEB-INF\classes\log4j.properties</param-value>
	</init-param>
	<load-on-startup>1</load-on-startup>
</servlet>

添加对应的servlet

Log4jInit.java

package com.suyang.servlet;

import java.io.IOException;

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

import org.apache.log4j.PropertyConfigurator;

/**
 * Servlet implementation class Log4jInit
 */
public class Log4jInit extends HttpServlet {
	private static final long serialVersionUID = 1L;

	@Override
	protected void doGet(HttpServletRequest req, HttpServletResponse resp)
			throws ServletException, IOException {
		// TODO Auto-generated method stub
		super.doGet(req, resp);
	}

	@Override
	protected void doPost(HttpServletRequest req, HttpServletResponse resp)
			throws ServletException, IOException {
		// TODO Auto-generated method stub
		super.doPost(req, resp);
	}

	@Override
	public void init() throws ServletException {
		// TODO Auto-generated method stub
		super.init();
		String prefix = getServletContext().getRealPath("/");
		String file = getInitParameter("log4j-init-file");
		if (file != null) {
			System.out.println("read log4j.properties:"+prefix + file);
			PropertyConfigurator.configure(prefix + file);
		}
	}

}

在resources中添加log4j.properties文件,maven会自动把文件复制到classes目录下

log4j.rootLogger = DEBUG , stdout , D

log4j.appender.stdout = org.apache.log4j.ConsoleAppender
log4j.appender.stdout.Target = System.out
log4j.appender.stdout.layout = org.apache.log4j.PatternLayout
log4j.appender.stdout.layout.ConversionPattern = %-d{yyyy-MM-dd HH:mm:ss} [ %t:%r ] - [ %p ] %m%n

log4j.appender.D = org.apache.log4j.DailyRollingFileAppender
log4j.appender.D.Threshold= DEBUG
log4j.appender.D.File= ${catalina.home}/logs/log.log
log4j.appender.D.ImmediateFlush= true
log4j.appender.D.Append= true
log4j.appender.D.DatePattern='-'yyyy-MM-dd-HH'.log'
log4j.appender.D.Encoding= UTF-8
log4j.appender.D.layout= org.apache.log4j.PatternLayout
log4j.appender.D.layout.ConversionPattern = %-d{yyyy-MM-dd HH:mm:ss} [ %t:%r ] - [ %p ] %m%n

日志会自动记录DEBUG级别以上的日志。

转载于:https://my.oschina.net/milletes/blog/1533847

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值