最近在做的一个项目是Servlet + Tomcat搭建的Dynamic Web,代码老旧,日志混乱,这里就记录一下如何在Dynamic Web中增加Log4j记录日志。
1 添加依赖包
首先,添加如下依赖包:
log4j-1.2.15.jar
slf4j-api-1.7.25.jar
slf4j-log4j12-1.7.25.jar
下载地址:https://pan.baidu.com/s/1Tkpv5XvUIWQf1Vb-Xr__Sg
提取密码:j9us
2 添加配置文件
在 /WEB-INF
文件夹下添加 log4j.properties
文件,文件内容如下:
#注意rootLogger的级别
log4j.rootLogger=INFO,stdout,infofile
#控制台日志
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{ISO8601}][%p]%l: %m%n
#INFO级别日志
#每天形成一个日志
log4j.appender.infofile=org.apache.log4j.DailyRollingFileAppender
log4j.appender.infofile.Append=true
#当前时间以前的日志为cmri_2019-03-08.log
log4j.appender.infofile.DatePattern='_'yyyy-MM-dd'.log'
#当前时间日志为cmri.log
log4j.appender.infofile.File=${catalina.home}/logs/cmri/cmri.log
log4j.appender.infofile.Threshold=INFO
log4j.appender.infofile.Encoding=UTF-8
log4j.appender.infofile.layout=org.apache.log4j.PatternLayout
#日志输出的格式,该格式为[时间][java类]代码行数:日志
log4j.appender.infofile.layout.ConversionPattern=[%d{ISO8601}][%p]%l: %m%n
#ERROR级别的日志
#log4j.appender.errorfile=org.apache.log4j.DailyRollingFileAppender
#log4j.appender.errorfile.Append=true
#log4j.appender.errorfile.DatePattern='_'yyyy-MM-dd-HH-mm'.log'
#log4j.appender.errorfile.File=${catalina.base}/logs/cmri/error/cmri_error.log
#log4j.appender.errorfile.Threshold=ERROR
#log4j.appender.errorfile.Encoding=UTF-8
#log4j.appender.errorfile.layout=org.apache.log4j.PatternLayout
#log4j.appender.errorfile.layout.ConversionPattern=[%d{ISO8601}][%p]%l: %m%n
#DEBUG级别的日志
#log4j.appender.debugfile=org.apache.log4j.DailyRollingFileAppender
#log4j.appender.debugfile.Append=true
#log4j.appender.debugfile.DatePattern='_'yyyy-MM-dd-HH-mm'.log'
#log4j.appender.debugfile.File=${catalina.base}/logs/cmri/debug/cmri_debug.log
#log4j.appender.debugfile.Threshold=DEBUG
#log4j.appender.debugfile.Encoding=UTF-8
#log4j.appender.debugfile.layout=org.apache.log4j.PatternLayout
#log4j.appender.debugfile.layout.ConversionPattern=[%d{ISO8601}][%p]%l: %m%n
可以设置多种级别的日志,分别记录到不同的日志文件中去。
Log4j根据日志信息的重要程度,分为不同的级别:OFF、FATAL、ERROR、WARN、INFO、DEBUG、ALL。官方建议实际使用时只使用四个级别,优先级从高到低分别是 ERROR、WARN、INFO、DEBUG。
上面我们指定INFO后DEBUG级别的日志就不再输出了。
这样可以对日志进行分级输出,例如:在测试环境中输出DEBUG级别的日志,在正式环境中不再输出DEBUG级别日志,只记录必要的信息。
3 添加log4j启动类
写一个log4j的启动类,代码如下:
package cm.kcloud.servlet;
import java.io.File;
import java.io.IOException;
import javax.servlet.ServletConfig;
import javax.servlet.ServletContext;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import org.apache.log4j.BasicConfigurator;
import org.apache.log4j.PropertyConfigurator;
@WebServlet("/Log4JInitServlet")
public class Log4JInitServlet extends HttpServlet {
private static final long serialVersionUID = 1L;
/**
* @see HttpServlet#HttpServlet()
*/
public Log4JInitServlet() {
super();
// TODO Auto-generated constructor stub
}
/**
* @see Servlet#init(ServletConfig)
*/
public void init(ServletConfig config) throws ServletException {
System.out.println("Log4JInitServlet 正在初始化 log4j日志设置信息");
String log4jLocation = config.getInitParameter("log4j-properties-location");
ServletContext sc = config.getServletContext();
if (log4jLocation == null) {
System.err.println("*** 没有 log4j-properties-location 初始化的文件, 所以使用 BasicConfigurator初始化");
BasicConfigurator.configure();
} else {
String webAppPath = sc.getRealPath("/");
String log4jProp = webAppPath + log4jLocation;
File yoMamaYesThisSaysYoMama = new File(log4jProp);
if (yoMamaYesThisSaysYoMama.exists()) {
System.out.println("使用: " + log4jProp+"初始化日志设置信息");
PropertyConfigurator.configure(log4jProp);
} else {
System.err.println("*** " + log4jProp + " 文件没有找到, 所以使用 BasicConfigurator初始化");
BasicConfigurator.configure();
}
}
super.init(config);
}
/**
* @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse response)
*/
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
// TODO Auto-generated method stub
}
/**
* @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse response)
*/
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
// TODO Auto-generated method stub
}
}
4 配置web.xml
在/WEB_INF/web.xml
文件中添加如下配置:
<!--用来启动 log4jConfigLocation的servlet -->
<servlet>
<servlet-name>Log4JInitServlet</servlet-name>
<servlet-class>cm.kcloud.servlet.Log4JInitServlet</servlet-class>
<init-param>
<param-name>log4j-properties-location</param-name>
<param-value>/WEB-INF/log4j.properties</param-value>
</init-param>
<load-on-startup>0</load-on-startup>
</servlet>
其中,<load-on-startup></load-on-startup>标签表示启动加载的顺序,0表示最先加载。
5 添加测试类
5.1 添加测试类,以测试log4j是否启用,代码如下:
package cm.kcloud.servlet;
import java.io.IOException;
import javax.servlet.ServletConfig;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import org.apache.log4j.Logger;
@WebServlet("/Log4JTestServlet")
public class Log4JTestServlet extends HttpServlet{
private static final long serialVersionUID = 1L;
private static final Logger logger = Logger.getLogger(Log4JTestServlet.class);
/**
* @see HttpServlet#HttpServlet()
*/
public Log4JTestServlet() {
super();
// TODO Auto-generated constructor stub
}
/**
* @see Servlet#init(ServletConfig)
*/
public void init(ServletConfig config) throws ServletException {
// TODO Auto-generated method stub
}
/**
* @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse response)
*/
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
// 记录debug级别的信息
logger.debug("This is debug message.");
// 记录info级别的信息
logger.info("这是 info message.");
// 记录error级别的信息
logger.error("This is error message.");
}
/**
* @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse response)
*/
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
doGet(request,response);
}
}
5.2 配置web.xml
将测试Servlet也配置到web.xml
文件中,代码如下:
<servlet>
<servlet-name>Log4JTestServlet</servlet-name>
<servlet-class>cm.kcloud.servlet.Log4JTestServlet</servlet-class>
</servlet>
<servlet-mapping>
<servlet-name>Log4JTestServlet</servlet-name>
<url-pattern>/log4j</url-pattern>
</servlet-mapping>
6 测试
启动项目后,在浏览器访问测试Servlet设置的url地址,如:http://localhost:8080/CMRI/log4j看日志是否被记录到相应的日志文件中。这里就不放截图了。
网友评论