JavaWeb学习笔记之Log4j使用教程
Posted 小明TI
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了JavaWeb学习笔记之Log4j使用教程相关的知识,希望对你有一定的参考价值。
一、入门实例
1.新建一个JAva工程,导入包log4j-1.2.17.jar,整个工程最终目录如下
2、src同级创建并设置log4j.properties
### 设置###
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
输出DEBUG 级别以上的日志到=E://logs/error.log
log4j.appender.D = org.apache.log4j.DailyRollingFileAppender
log4j.appender.D.File = E://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
输出ERROR 级别以上的日志到=E://logs/error.log
log4j.appender.E = org.apache.log4j.DailyRollingFileAppender
log4j.appender.E.File =E://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
3、设置日志内容
package com.mucfc;
import org.apache.log4j.Logger;
/**
*@author linbingwen
*@2015年5月18日9:14:21
*/
public class Test {
private static Logger logger = Logger.getLogger(Test.class);
/**
* @param args
*/
public static void main(String[] args) {
// System.out.println("This is println message.");
// 记录debug级别的信息
logger.debug("This is debug message.");
// 记录info级别的信息
logger.info("This is info message.");
// 记录error级别的信息
logger.error("This is error message.");
}
}
4、输出结果
(1)首先是控制台的信息
三、Web项目中使用Log4j实例
上面代码描述了Log4j的简单应用,其实使用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="http://www.w3.org/2001/XMLSchema-instance"
xmlns="http://java.sun.com/xml/ns/javaee"
xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_3_0.xsd"
id="WebApp_ID" version="3.0">
<display-name>LogLearning</display-name>
<servlet>
<servlet-name>Log4JTestServlet</servlet-name>
<servlet-class>com.mucfc.Log4JTestServlet</servlet-class>
</servlet>
<!--用来启动 log4jConfigLocation的servlet -->
<servlet>
<servlet-name>Log4JInitServlet</servlet-name>
<servlet-class>com.mucfc.Log4JInitServlet</servlet-class>
<init-param>
<param-name>log4j-properties-location</param-name>
<param-value>/WEB-INF/classes/log4j.properties</param-value>
</init-param>
<load-on-startup>1</load-on-startup>
</servlet>
<servlet-mapping>
<servlet-name>Log4JTestServlet</servlet-name>
<url-pattern>/test</url-pattern>
</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);
}
}
四、Spring中使用Log4j
这里要实现web项目中利用Spring来使用Log4j
(1)接上面的工程,然后再导入Spring的包
(2)web.xml增加
<!-- 设置根目录 -->
<context-param>
<param-name>webAppRootKey</param-name>
<param-value>webapp.root</param-value>
</context-param>
<context-param>
<param-name>log4jConfigLocation</param-name>
<param-value>/WEB-INF/classes/log4j.properties</param-value>
</context-param>
<!-- 3000表示 开一条watchdog线程每60秒扫描一下配置文件的变化;这样便于日志存放位置的改变 -->
<context-param>
<param-name>log4jRefreshInterval</param-name>
<param-value>3000</param-value>
</context-param>
<listener>
<listener-class>org.springframework.web.util.Log4jConfigListener</listener-class>
</listener>
整个内容如下:
<?xml version="1.0" encoding="UTF-8"?>
<web-app xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns="http://java.sun.com/xml/ns/javaee"
xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_3_0.xsd"
id="WebApp_ID" version="3.0">
<display-name>LogLearning</display-name>
<servlet>
<servlet-name>Log4JTestServlet</servlet-name>
<servlet-class>com.mucfc.Log4JTestServlet</servlet-class>
</servlet>
<!--用来启动 log4jConfigLocation的servlet -->
<!-- <servlet>
<servlet-name>Log4JInitServlet</servlet-name>
<servlet-class>com.mucfc.Log4JInitServlet</servlet-class>
<init-param>
<param-name>log4j-properties-location</param-name>
<param-value>/WEB-INF/classes/log4j.properties</param-value>
</init-param>
<load-on-startup>1</load-on-startup>
</servlet>-->
<servlet-mapping>
<servlet-name>Log4JTestServlet</servlet-name>
<url-pattern>/test</url-pattern>
</servlet-mapping>
<!-- Spring 容器加载 -->
<listener>
<listener-class>org.springframework.web.context.ContextLoaderListener</listener-class>
</listener>
<context-param>
<param-name>contextConfigLocation</param-name>
<param-value>classpath:applicationContext.xml</param-value>
</context-param>
<!-- 设置根目录 -->
<context-param>
<param-name>webAppRootKey</param-name>
<param-value>webapp.root</param-value>
</context-param>
<context-param>
<param-name>log4jConfigLocation</param-name>
<param-value>/WEB-INF/classes/log4j.properties</param-value>
</context-param>
<!-- 3000表示 开一条watchdog线程每60秒扫描一下配置文件的变化;这样便于日志存放位置的改变 -->
<context-param>
<param-name>log4jRefreshInterval</param-name>
<param-value>3000</param-value>
</context-param>
<listener>
<listener-class>org.springframework.web.util.Log4jConfigListener</listener-class>
</listener>
</web-app>
这里Log4JInitServlet.java就相当于没用到了。
(2)applicationContext.xml
没有内容:
<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:context="http://www.springframework.org/schema/context"
xmlns:aop="http://www.springframework.org/schema/aop"
xsi:schemaLocation="
http://www.springframework.org/schema/beans
http://www.springframework.org/schema/beans/spring-beans-3.2.xsd
http://www.springframework.org/schema/aop
http://www.springframework.org/schema/aop/spring-aop-3.2.xsd
http://www.springframework.org/schema/context
http://www.springframework.org/schema/context/spring-context-3.2.xsd">
</beans>
以上是关于JavaWeb学习笔记之Log4j使用教程的主要内容,如果未能解决你的问题,请参考以下文章