Log4j 生成日志文件(路径)

时间:2022-12-22 17:10:30


将日志文件生成到项目的某一级目录下,常用的有两种方法:


1. 使用spring集成log4j 配置 webapp.root 参数

2. 使用 System.setProperty 来设置系统属性 webapp.root  

(1)Java代码

package iot.servlet;
import javax.servlet.ServletConfig;
import javax.servlet.ServletContext;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;

import org.apache.log4j.BasicConfigurator;

public class Log4JInitServlet extends HttpServlet {
private static final long serialVersionUID = 1L;

public void init(ServletConfig config) throws ServletException {
ServletContext sc = config.getServletContext();
String webAppPath = sc.getRealPath("/");
System.setProperty("webapp.root", webAppPath);
BasicConfigurator.configure();

super.init(config);
}

}

(2)web.xml 代码

  <context-param>
    <param-name>log4jConfigLocation</param-name>
    <param-value>/WEB-INF/classes/log4j.properties</param-value>
  </context-param>

  <servlet>
    <servlet-name>Log4JInitServlet</servlet-name>
    <servlet-class>iot.servlet.Log4JInitServlet</servlet-class>
    <load-on-startup>1</load-on-startup>
  </servlet>
 

(3)log4j.properties 代码

log4j.rootLogger=INFO, LogFile,stdout

log4j.appender.LogFile=org.apache.log4j.DailyRollingFileAppender
log4j.appender.LogFile.ImmediateFlush=true
log4j.appender.LogFile.Append=true
log4j.appender.LogFile.File=${webapp.root}/logs/mylog123.log
log4j.appender.LogFile.DatePattern=yyyy-MM-dd'.txt'
log4j.appender.LogFile.layout=org.apache.log4j.PatternLayout
log4j.appender.LogFile.layout.ConversionPattern=[%-5p] %d{yyyy-MM-dd HH\:mm\:ss} -> %l\: %m %n

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

log4j.logger.org.apache=ALL