您当前的位置:移动互联培训 > Java培训 > JAVA开发 >
Web项目中使用Log4j实例
来源:华清远见JAVA学院 2017-05-12Web项目中如何使用Log4j呢?做一个J2EE应用,在J2EE应用使用Log4j,必须先在启动服务时加载Log4j的配置文件进行初始化,可以在web.xml中进行。
1、web应用的log4j使用基本上都采用:新建一个servlet,这个servlet在init函数中为log4j执行配置。一般就是读入配置文件。所以需要在web.xml中为这个servlet配置,同时设定load-on-startup为1。
2、这个servlet配置log4j就是读出配置文件,然后调用configure函数。这里有两个问题:一、需要知道文件在哪里;二、需要正确的文件类型
3、配置文件位置在web.xml中配置一个param即可,路径一般是相对于web的root目录
4、文件类型一般有两种,一个是Java的property文件,另一种是xml文件
配置文件的大致内容:log4j可以指定输出的log级别的低等级,以及log的输出配置格式,每个log可以指定多个输出方式
(1)创建Web工程,整个工程后目录如下
(2)web.xml配置如下:
<?xml version="1.0" encoding="UTF-8"?>
<web-app xmlns:xsi=“//www.w3.org/2001/XMLSchema-instance”
xmlns="//java.sun.com/xml/ns/javaee"
xsi:schemaLocation="//java.sun.com/xml/ns/javaee //java.sun.com/xml/ns/javaee/web-app_3_0.xsd"
id="WebApp_ID" version="3.0">
<servlet-name>Log4JTestServlet</servlet-name>
<servlet-class>com.mucfc.Log4JTestServlet</servlet-class>
</servlet>
<!--用来启动log4jConfigLocation的servlet-->
<servlet-name>Log4JInitServlet</servlet-name>
<param-name>log4j-properties-location</param-name>
<load-on-startup>1</load-on-startup>
</servlet>
<servlet-mapping>
</servlet-mapping>
</web-app>
(3)配置文件log4j.properties
### set log levels ###
log4j.rootLogger = debug,stdout,D,E
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 = [%-5p] %d{yyyy-MM-dd HH:mm:ss,SSS} method:%l%n%m%n
log4j.appender.D = org.apache.log4j.DailyRollingFileAppender
log4j.appender.D.File = F://logs/log.log
log4j.appender.D.Append = true
log4j.appender.D.Threshold = DEBUG
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
log4j.appender.E = org.apache.log4j.DailyRollingFileAppender
log4j.appender.E.File =F://logs/error.log
log4j.appender.E.Append = true
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} [ %t:%r ] - [ %p ] %m%n
(4)web容器一来就初始化的servlet
Log4JInitServlet.java
package com.mucfc;
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;
/**
* Servlet implementation class Log4JInitServlet
*/
@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
}}
调用日志Log4JTestServlet,java
package com.mucfc;
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;
/**
* Servlet implementation class Log4JTestServlet
*/
@WebServlet("/Log4JTestServlet")
public class Log4JTestServlet extends HttpServlet {
private static final long serialVersionUID = 1L;
private static 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("This is 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);
}}
接下来就是运行了,来看看结果:
输出结果:
相关内容推荐:log4j使用教程详解 Log4j使用案例
每当谈到JavaEE开发,很多初学者就认为JavaEE就是JAVA语言,这么想其实也没错,但多了俩个E,其实差距还是...
每当谈到JAVAEE开发,很多初学者就认为JAVAEE就是JAVA语言,这么想其实也没错,但多了俩个E,其实差距还是...
JVM在Java应用程序优化中是不可缺少的一项,如何合理配置Java参数,如何验证配置参数的有效性,从GC日志中...
Copyright ©2004-2018 华清远见教育科技集团 版权所有
京ICP备16055225号,京公海网安备11010802025203号