关于java web项目使用log4j
关于java web项目使用log4j
非沧海一粟不随波逐流 发表于3个月前
关于java web项目使用log4j
  • 发表于 3个月前
  • 阅读 1
  • 收藏 0
  • 点赞 0
  • 评论 0

腾讯云 技术升级10大核心产品年终让利>>>   

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级别以上的日志。

共有 人打赏支持
粉丝 0
博文 48
码字总数 1751
×
非沧海一粟不随波逐流
如果觉得我的文章对您有用,请随意打赏。您的支持将鼓励我继续创作!
* 金额(元)
¥1 ¥5 ¥10 ¥20 其他金额
打赏人
留言
* 支付类型
微信扫码支付
打赏金额:
已支付成功
打赏金额: