一、入门实例
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
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
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配置如下:
"1.0" encoding="UTF-8"?>
"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">
LogLearning
Log4JTestServlet
class>com.mucfc.Log4JTestServlet class>
Log4JInitServlet
class>com.mucfc.Log4JInitServlet class>
log4j-properties-location
/WEB-INF/classes/log4j.properties
1
Log4JTestServlet
/test
(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>webAppRootKeyparam-name>
<param-value>webapp.rootparam-value>
context-param>
<context-param>
<param-name>log4jConfigLocationparam-name>
<param-value>/WEB-INF/classes/log4j.propertiesparam-value>
context-param>
<context-param>
<param-name>log4jRefreshIntervalparam-name>
<param-value>3000param-value>
context-param>
<listener>
<listener-class>org.springframework.web.util.Log4jConfigListenerlistener-class>
listener>
整个内容如下:
<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>LogLearningdisplay-name>
<servlet>
<servlet-name>Log4JTestServletservlet-name>
<servlet-class>com.mucfc.Log4JTestServletservlet-class>
servlet>
<servlet-mapping>
<servlet-name>Log4JTestServletservlet-name>
<url-pattern>/testurl-pattern>
servlet-mapping>
<listener>
<listener-class>org.springframework.web.context.ContextLoaderListenerlistener-class>
listener>
<context-param>
<param-name>contextConfigLocationparam-name>
<param-value>classpath:applicationContext.xmlparam-value>
context-param>
<context-param>
<param-name>webAppRootKeyparam-name>
<param-value>webapp.rootparam-value>
context-param>
<context-param>
<param-name>log4jConfigLocationparam-name>
<param-value>/WEB-INF/classes/log4j.propertiesparam-value>
context-param>
<context-param>
<param-name>log4jRefreshIntervalparam-name>
<param-value>3000param-value>
context-param>
<listener>
<listener-class>org.springframework.web.util.Log4jConfigListenerlistener-class>
listener>
web-app>
这里Log4JInitServlet.java就相当于没用到了。
(2)applicationContext.xml
没有内容:
<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使用教程