log4j日志文件路径问题

时间:2022-04-28 09:51:14

做了一个最简单的servlet项目,只有一个servlet,然后想在servlet把日志记录到项目下的logs文件夹中的logRecord.log和logRecorderror.log。

然而路径问题弄了我一天,找了很多资料,绝对路径是可以解决,但是如果移植的话,那么绝对路径改起来会很麻烦。所以最好用相对路径。


但是网上的相关资料都无法解决我的问题,后来一不做二不休,瞎弄,发现路径直接写logs/logRecord.log竟然成功的把日志写入进去了。


好了,话不多说   直接上代码。


1.首先我们把

commons-logging-1.1.3.jar
log4j-1.2.17.jar

导入到项目中。


2.配置log4j.properties

### set log levels ###
log4j.rootLogger = INFO, stdout, D, E
#log4j.rootLogger = INFO, stdout
#log.path = /mylog

###ãè¾åºå°æ§å¶å° ###
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} [%-5p] [%c] [%F] - %m %n

### è¾åºå°æ¥å¿æ件 ###
log4j.appender.D = org.apache.log4j.DailyRollingFileAppender
log4j.appender.D.File = logs/logRecord.log
log4j.appender.D.DatePattern='.'yyyy-MM-dd
log4j.appender.D.Threshold = INFO
log4j.appender.D.layout = org.apache.log4j.PatternLayout
log4j.appender.D.layout.ConversionPattern = %d{yyyy/MM/dd-HH:mm:ss} [%-5p] [%c] [%F] - %m %n
log4j.appender.D.layout.Encoding=UTF-8

### ä¿å­å¼å¸¸ä¿¡æ¯å°åç¬æ件 ###
log4j.appender.E = org.apache.log4j.DailyRollingFileAppender
##å¼å¸¸æ¥å¿æ件
log4j.appender.E.File = logs/logRecorderror.log
log4j.appender.E.Append = true
##åªè¾åºERROR级å«ä»¥ä¸çæ¥å¿
log4j.appender.E.Threshold = ERROR 
log4j.appender.E.layout = org.apache.log4j.PatternLayout
log4j.appender.E.layout.ConversionPattern = %d{yyyy/MM/dd-HH:mm:ss} [%-5p] [%c] [%F] - %m %n
log4j.appender.E.DatePattern='.'yyyy-MM-dd
log4j.appender.E.Encoding=UTF-8



这个是servlet,里面的main方法是来把日志写入文件中。

package com.pingpay.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.commons.logging.Log;
import org.apache.commons.logging.LogFactory;

public class PingPayLogServlet extends HttpServlet {

	// 在任何需要记录日志的类中

	Log log = LogFactory.getLog(this.getClass());

	/**
	 * 记录ping++返回的数据
	 * 
	 */
	public void doPost(HttpServletRequest request, HttpServletResponse response)
			throws ServletException, IOException {

//		response.setContentType("text/html");
//		request.setCharacterEncoding("utf-8");
//		response.setCharacterEncoding("utf-8");

		log.info("into one method");

		try {

			System.out.println(9 / 0);

		} catch (RuntimeException e) {

			log.error(e.getMessage());

		}

		log.info("out one method");

	}

	public static void main(String[] args) throws Exception {
		new PingPayLogServlet().doPost(null, null);
		System.out.println("1");
	}

}


log4j日志文件路径问题

log4j日志文件路径问题

项目结构如图。


因为我们在log4j.properties中设置了log4j.appender.D.Threshold = INFO,log4j.appender.E.Threshold = ERROR 。

所以error的日志会保存在logRecorderror.log文件中,

但是由于:DEBUG < INFO < WARN < ERROR < FATAL级别

log4j.appender.D.Threshold = INFO这句话 
它的作用是输出INFO级别以上的内容到logRecord.log中,所以logRecord.log文件中包含了ERROR级别的文件。


如有错误,请指出,谢谢。


周一回来发现上面的方法不行了。我也是醉了,然后换了一种方法。

将日志文件输出到自己程序WEB-INF\logs目录中

1、在web.xml配置一个servlet

<servlet>
 	<servlet-name>lo4jInit</servlet-name>
 	<servlet-class>com.linder.util.log4j.init.Lo4jInit</servlet-class>
 	<init-param>
 		<param-name>log4j_init_path</param-name>
 		<param-value>WEB-INF\classes\log4j.properties</param-value>
 	</init-param>
 	<init-param>
 		<param-name>log4j_file_path</param-name>
 		<param-value>WEB-INF\logs\</param-value>
 	</init-param>
 	<load-on-startup>0</load-on-startup>
 </servlet>

2、编写一个初始化log4j的Servlet

package com.linder.util.log4j.init;

import java.io.FileInputStream;
import java.io.IOException;
import java.util.Properties;

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

import org.apache.log4j.Logger;
import org.apache.log4j.PropertyConfigurator;


public class Lo4jInit   extends HttpServlet {

	/**
	 * 
	 */
	private static final long serialVersionUID = 1L;
	private static Logger logger=Logger.getLogger(Lo4jInit.class);
	
	public void init(){
		String path=this.getServletContext().getRealPath("/");
		String file=this.getInitParameter("log4j_init_path");
		String logFile=this.getInitParameter("log4j_file_path");
		if(file!=null)
		{
			Properties prop = new Properties(); 
			try{
				prop.load(new FileInputStream(path+file)); //加载log4j.properties
				prop.setProperty("log4j.appender.R.File", path+logFile+ prop.getProperty("log4j.appender.R.File")); //设置日志文件的输出路径
				PropertyConfigurator.configure(prop); //加载配置项
			}catch(Exception e)
			{
				logger.info("初始化log4j日志输入路径异常,请检查web.xml参数配置是否正常,异常发生在"+this.getClass().getName()+"类的public void init()方法,异常的愿意是:"+e.getMessage(), e.fillInStackTrace());
			}
		}
		

	}
	protected void service(HttpServletRequest request, HttpServletResponse response)
	throws ServletException, IOException {
		
	}

}

 3、log4j.properties的配置信息

# Set root category priority to info and its only appender to console. 
log4j.rootCategory=info,console,R
#log4j.debug=true

# console is set to be a ConsoleAppender using a PatternLayout. 
log4j.appender.console=org.apache.log4j.ConsoleAppender 
log4j.appender.console.Threshold=info 
log4j.appender.console.layout=org.apache.log4j.PatternLayout 
log4j.appender.console.layout.ConversionPattern=- %m%n

# R is set to be a File appender using a PatternLayout.
log4j.appender.R=org.apache.log4j.RollingFileAppender
log4j.appender.R.Append=true
log4j.appender.R.Threshold=info 
log4j.appender.R.MaxFileSize=1024KB 
log4j.appender.R.MaxBackupIndex=10
log4j.appender.R.File=abc.log
log4j.appender.R.layout=org.apache.log4j.PatternLayout
log4j.appender.R.layout.ConversionPattern=%-d{yyyy-MM-dd HH\:mm\:ss} [%c]-[%p] %m%n

abc.log位于你项目的WEB-INF/logs的文件夹下。


 我项目的XML配置为:

<?xml version="1.0" encoding="UTF-8"?>
<web-app version="3.0" xmlns="http://java.sun.com/xml/ns/javaee"
	xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
	xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_3_0.xsd">

	<servlet>
		<servlet-name>lo4jInit</servlet-name>
		<servlet-class>com.pingpay.servlet.Lo4jInit</servlet-class>
		<init-param>
			<param-name>log4j_init_path</param-name>
			<param-value>WEB-INF\classes\log4j.properties</param-value>
		</init-param>
		<init-param>
			<param-name>log4j_file_path</param-name>
			<param-value>WEB-INF\logs\</param-value>
		</init-param>
		<load-on-startup>0</load-on-startup>
	</servlet>

	<servlet>
		<description>This is the description of my J2EE component</description>
		<display-name>This is the display name of my J2EE component</display-name>
		<servlet-name>PingPayServlet</servlet-name>
		<servlet-class>com.pingpay.servlet.PingPayServlet</servlet-class>
	</servlet>

	<servlet-mapping>
		<servlet-name>PingPayServlet</servlet-name>
		<url-pattern>/PingPayServlet</url-pattern>
	</servlet-mapping>


</web-app>