最详细的Log4j使用教程

本文涉及的产品
日志服务 SLS,月写入数据量 50GB 1个月
简介:

日志是应用软件中不可缺少的部分,Apache的开源项目log4j是一个功能强大的日志组件,提供方便的日志记录。在apache网站:jakarta.apache.org/log4j 可以免费下载到Log4j最新版本的软件包。

一、入门实例

1.新建一个JAva工程,导入包log4j-1.2.17.jar,整个工程最终目录如下

2、src同级创建并设置log4j.properties

<span class= "hljs-comment" > ### 设置###
<span class= "hljs-built_in" >log4j.rootLogger = debug,stdout,D,E
 
<span class= "hljs-comment" > ### 输出信息到控制抬 ###
<span class= "hljs-built_in" >log4j.appender.stdout = org.apache.log4j.ConsoleAppender
<span class= "hljs-built_in" >log4j.appender.stdout.Target = System.out
<span class= "hljs-built_in" >log4j.appender.stdout.layout = org.apache.log4j.PatternLayout
<span class= "hljs-built_in" >log4j.appender.stdout.layout.ConversionPattern = [%-5p] %d{yyyy-MM- dd  HH:mm:ss,SSS} method:%l%n%m%n
 
<span class= "hljs-comment" > ### 输出DEBUG 级别以上的日志到=E://logs/error.log ###
<span class= "hljs-built_in" >log4j.appender.D = org.apache.log4j.DailyRollingFileAppender
<span class= "hljs-built_in" >log4j.appender.D.File = E: //logs/log .log
<span class= "hljs-built_in" >log4j.appender.D.Append = <span class= "hljs-literal" > true
<span class= "hljs-built_in" >log4j.appender.D.Threshold = DEBUG
<span class= "hljs-built_in" >log4j.appender.D.layout = org.apache.log4j.PatternLayout
<span class= "hljs-built_in" >log4j.appender.D.layout.ConversionPattern = %<span class= "hljs-_" >-d{yyyy-MM- dd  HH:mm:ss}  [ %t:%r ] - [ %p ]  %m%n
 
<span class= "hljs-comment" > ### 输出ERROR 级别以上的日志到=E://logs/error.log ###
<span class= "hljs-built_in" >log4j.appender.E = org.apache.log4j.DailyRollingFileAppender
<span class= "hljs-built_in" >log4j.appender.E.File =E: //logs/error .log
<span class= "hljs-built_in" >log4j.appender.E.Append = <span class= "hljs-literal" > true
<span class= "hljs-built_in" >log4j.appender.E.Threshold = ERROR
<span class= "hljs-built_in" >log4j.appender.E.layout = org.apache.log4j.PatternLayout
<span class= "hljs-built_in" >log4j.appender.E.layout.ConversionPattern = %<span class= "hljs-_" >-d{yyyy-MM- dd  HH:mm:ss}  [ %t:%r ] - [ %p ]  %m%n< /span >< /span >< /span >< /span >< /span >< /span >< /span >< /span >< /span >< /span >< /span >< /span >< /span >< /span >< /span >< /span >< /span >< /span >< /span >< /span >< /span >< /span >< /span >< /span >< /span >

3、设置日志内容

<span class = "hljs-keyword" > package  com.mucfc;
<span class = "hljs-keyword" > import  org.apache.log4j.Logger;
<span class = "hljs-comment" > /**
  *<span class="hljs-doctag">@author linbingwen
  *@2015年5月18日9:14:21
  */
<span class = "hljs-keyword" > public  <span class = "hljs-class" ><span class = "hljs-keyword" > class  <span class = "hljs-title" >Test {
     <span class = "hljs-keyword" > private  <span class = "hljs-keyword" > static  Logger logger = Logger.getLogger(Test. class ); 
 
     <span class = "hljs-comment" > /**
      * <span class="hljs-doctag">@param args
      */ 
     <span class = "hljs-function" ><span class = "hljs-keyword" > public  <span class = "hljs-keyword" > static  <span class = "hljs-keyword" > void  <span class = "hljs-title" >main<span class = "hljs-params" >(String[] args) { 
         <span class = "hljs-comment" > // System.out.println("This is println message."); 
 
         <span class = "hljs-comment" > // 记录debug级别的信息 
         logger.debug(<span class = "hljs-string" > "This is debug message." ); 
         <span class = "hljs-comment" > // 记录info级别的信息 
         logger.info(<span class = "hljs-string" > "This is info message." ); 
         <span class = "hljs-comment" > // 记录error级别的信息 
         logger.error(<span class = "hljs-string" > "This is error message." ); 
    
 
}</span></span></span></span></span></span></span></span></span></span></span></span></span></span></span></span></span></span></span></span></span></span></span></span></span>

4、输出结果

(1)首先是控制台的信息

(2)再来看输出的文件

内容如下,发现已按照要求输出到对应的文档中去了。

二、Log4j基本使用方法

Log4j由三个重要的组件构成:日志信息的优先级,日志信息的输出目的地,日志信息的输出格式。日志信息的优先级从高到低有ERROR、WARN、 INFO、DEBUG,分别用来指定这条日志信息的重要程度;日志信息的输出目的地指定了日志将打印到控制台还是文件中;而输出格式则控制了日志信息的显 示内容。

2.1、定义配置文件

其实您也可以完全不使用配置文件,而是在代码中配置Log4j环境。但是,使用配置文件将使您的应用程序更加灵活。Log4j支持两种配置文件格式,一种是XML格式的文件,一种是Java特性文件(键=值)。下面我们介绍使用Java特性文件做为配置文件的方法:
1.配置根Logger,其语法为:

<span class = "hljs-built_in" >log4j.rootLogger = [ level ] , appenderName, appenderName, …</span>

其中,level 是日志记录的优先级,分为OFF、FATAL、ERROR、WARN、INFO、DEBUG、ALL或者您定义的级别。Log4j建议只使用四个级别,优 先级从高到低分别是ERROR、WARN、INFO、DEBUG。通过在这里定义的级别,您可以控制到应用程序中相应级别的日志信息的开关。比如在这里定 义了INFO级别,则应用程序中所有DEBUG级别的日志信息将不被打印出来。 appenderName就是指B日志信息输出到哪个地方。您可以同时指定多个输出目的地。

2.配置日志信息输出目的地Appender,其语法为:

<span class = "hljs-built_in" >log4j.appender.appenderName = fully.qualified.name.of.appender. class 
<span class = "hljs-built_in" >log4j.appender.appenderName.option1 = value1 
… 
<span class = "hljs-built_in" >log4j.appender.appenderName.option = valueN</span></span></span>

其中,Log4j提供的appender有以下几种:

<span class = "hljs-selector-tag" >org<span class = "hljs-selector-class" >.apache<span class = "hljs-selector-class" >.log4j<span class = "hljs-selector-class" >.ConsoleAppender(控制台), 
<span class = "hljs-selector-tag" >org<span class = "hljs-selector-class" >.apache<span class = "hljs-selector-class" >.log4j<span class = "hljs-selector-class" >.FileAppender(文件), 
<span class = "hljs-selector-tag" >org<span class = "hljs-selector-class" >.apache<span class = "hljs-selector-class" >.log4j<span class = "hljs-selector-class" >.DailyRollingFileAppender(每天产生一个日志文件), 
<span class = "hljs-selector-tag" >org<span class = "hljs-selector-class" >.apache<span class = "hljs-selector-class" >.log4j<span class = "hljs-selector-class" >.RollingFileAppender(文件大小到达指定尺寸的时候产生一个新的文件), 
<span class = "hljs-selector-tag" >org<span class = "hljs-selector-class" >.apache<span class = "hljs-selector-class" >.log4j<span class = "hljs-selector-class" >.WriterAppender(将日志信息以流格式发送到任意指定的地方)</span></span></span></span></span></span></span></span></span></span></span></span></span></span></span></span></span></span></span></span>

3.配置日志信息的格式(布局),其语法为:

<span class = "hljs-built_in" >log4j.appender.appenderName.layout = fully.qualified.name.of.layout. class 
<span class = "hljs-built_in" >log4j.appender.appenderName.layout.option1 = value1 
… 
<span class = "hljs-built_in" >log4j.appender.appenderName.layout.option = valueN</span></span></span>

其中,Log4j提供的layout有以e几种:

<span class = "hljs-selector-tag" >org<span class = "hljs-selector-class" >.apache<span class = "hljs-selector-class" >.log4j<span class = "hljs-selector-class" >.HTMLLayout(以<span class = "hljs-selector-tag" >HTML表格形式布局), 
<span class = "hljs-selector-tag" >org<span class = "hljs-selector-class" >.apache<span class = "hljs-selector-class" >.log4j<span class = "hljs-selector-class" >.PatternLayout(可以灵活地指定布局模式), 
<span class = "hljs-selector-tag" >org<span class = "hljs-selector-class" >.apache<span class = "hljs-selector-class" >.log4j<span class = "hljs-selector-class" >.SimpleLayout(包含日志信息的级别和信息字符串), 
<span class = "hljs-selector-tag" >org<span class = "hljs-selector-class" >.apache<span class = "hljs-selector-class" >.log4j<span class = "hljs-selector-class" >.TTCCLayout(包含日志产生的时间、线程、类别等等信息)</span></span></span></span></span></span></span></span></span></span></span></span></span></span></span></span></span>

Log4J采用类似C语言中的printf函数的打印格式格式化日志信息,打印参数如下: %m 输出代码中指定的消息

%p 输出优先级,即DEBUG,INFO,WARN,ERROR,FATAL 
%r 输出自应用启动到输出该<span class= "hljs-keyword" >log信息耗费的毫秒数 
%c 输出所属的类目,通常就是所在类的全名 
%t 输出产生该日志事件的线程名 
%n 输出一个回车换行符,Windows平台为“rn”,Unix平台为“n” 
%d 输出日志时间点的日期或时间,默认格式为ISO8601,也可以在其后指定格式,比如:%d{yyy MMM dd  HH:mm:ss,SSS},输出类似:<span class= "hljs-number" >2002年<span class= "hljs-number" >10月<span class= "hljs-number" >18日 <span class= "hljs-number" >22:<span class= "hljs-number" >10:<span class= "hljs-number" >28,<span class= "hljs-number" >921 
%l 输出日志事件的发生位置,包括类目名、发生的线程,以及在代码中的行数。举例:Testlog4.main(TestLog4.java:<span class= "hljs-number" >10)< /span >< /span >< /span >< /span >< /span >< /span >< /span >< /span >< /span >

2.2、在代码中使用Log4j

1.得到记录器

使用Log4j,第一步就是获取日志记录器,这个记录器将负责控制日志信息。其语法为:

public static Logger getLogger( String name)

通过指定的名字获得记录器,如果必要的话,则为这个名字创建一个新的记录器。Name一般取本类的名字,比如:

static Logger logger = Logger.getLogger ( ServerWithLog4j.class.getName () )

2.读取配置文件

当获得了日志记录器之后,第二步将配置Log4j环境,其语法为:

<span class = "hljs-selector-tag" >BasicConfigurator<span class = "hljs-selector-class" >.configure (): 自动快速地使用缺省<span class = "hljs-selector-tag" >Log4j环境。 
<span class = "hljs-selector-tag" >PropertyConfigurator<span class = "hljs-selector-class" >.configure ( <span class = "hljs-selector-tag" >String <span class = "hljs-selector-tag" >configFilename) :读取使用<span class = "hljs-selector-tag" >Java的特性文件编写的配置文件。 
<span class = "hljs-selector-tag" >DOMConfigurator<span class = "hljs-selector-class" >.configure ( <span class = "hljs-selector-tag" >String <span class = "hljs-selector-tag" >filename ) :读取<span class = "hljs-selector-tag" >XML形式的配置文件。</span></span></span></span></span></span></span></span></span></span></span></span></span>

3.插入记录信息(格式化日志信息)

当上两个必要步骤执行完毕,您就可以轻松地使用不同优先级别的日志记录语句插入到您想记录日志的任何地方,其语法如下:

<span class = "hljs-selector-tag" >Logger<span class = "hljs-selector-class" >.debug ( <span class = "hljs-selector-tag" >Object <span class = "hljs-selector-tag" >message ) ; 
<span class = "hljs-selector-tag" >Logger<span class = "hljs-selector-class" >.info ( <span class = "hljs-selector-tag" >Object <span class = "hljs-selector-tag" >message ) ; 
<span class = "hljs-selector-tag" >Logger<span class = "hljs-selector-class" >.warn ( <span class = "hljs-selector-tag" >Object <span class = "hljs-selector-tag" >message ) ; 
<span class = "hljs-selector-tag" >Logger<span class = "hljs-selector-class" >.error ( <span class = "hljs-selector-tag" >Object <span class = "hljs-selector-tag" >message ) ;</span></span></span></span></span></span></span></span></span></span></span></span></span></span></span></span>

2.3、日志级别

每个Logger都被了一个日志级别(log level),用来控制日志信息的输出。日志级别从高到低分为:
A:off 最高等级,用于关闭所有日志记录。
B:fatal 指出每个严重的错误事件将会导致应用程序的退出。
C:error 指出虽然发生错误事件,但仍然不影响系统的继续运行。
D:warm 表明会出现潜在的错误情形。
E:info 一般和在粗粒度级别上,强调应用程序的运行全程。
F:debug 一般用于细粒度级别上,对调试应用程序非常有帮助。
G:all 最低等级,用于打开所有日志记录。

上面这些级别是定义在org.apache.log4j.Level类中。Log4j只建议使用4个级别,优先级从高到低分别是error,warn,info和debug。通过使用日志级别,可以控制应用程序中相应级别日志信息的输出。例如,如果使用b了info级别,则应用程序中所有低于info级别的日志信息(如debug)将不会被打印出来。

三、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配置如下:

< span  class="php">< span  class="hljs-meta"><? xml  version=<span class="hljs-string">"1.0" encoding=< span  class="hljs-string">"UTF-8"< span  class="hljs-meta">?> 
< span  class="hljs-tag"><< span  class="hljs-name">web-app < span  class="hljs-attr">xmlns:xsi=< span  class="hljs-string">"http://www.w3.org/2001/XMLSchema-instance" 
     < span  class="hljs-attr">xmlns=< span  class="hljs-string">"http://java.sun.com/xml/ns/javaee" 
     < span  class="hljs-attr">xsi:schemaLocation=< span  class="hljs-string">"http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_3_0.xsd" 
     < span  class="hljs-attr">id=< span  class="hljs-string">"WebApp_ID" < span  class="hljs-attr">version=< span  class="hljs-string">"3.0"> 
     < span  class="hljs-tag"><< span  class="hljs-name">display-name>LogLearning< span  class="hljs-tag"></< span  class="hljs-name">display-name> 
 
     < span  class="hljs-tag"><< span  class="hljs-name">servlet> 
         < span  class="hljs-tag"><< span  class="hljs-name">servlet-name>Log4JTestServlet< span  class="hljs-tag"></< span  class="hljs-name">servlet-name> 
         < span  class="hljs-tag"><< span  class="hljs-name">servlet-class>com.mucfc.Log4JTestServlet< span  class="hljs-tag"></< span  class="hljs-name">servlet-class> 
     < span  class="hljs-tag"></< span  class="hljs-name">servlet> 
 
     < span  class="hljs-comment"> <!--用来启动 log4jConfigLocation的servlet --> 
     < span  class="hljs-tag"><< span  class="hljs-name">servlet> 
         < span  class="hljs-tag"><< span  class="hljs-name">servlet-name>Log4JInitServlet< span  class="hljs-tag"></< span  class="hljs-name">servlet-name> 
         < span  class="hljs-tag"><< span  class="hljs-name">servlet-class>com.mucfc.Log4JInitServlet< span  class="hljs-tag"></< span  class="hljs-name">servlet-class> 
         < span  class="hljs-tag"><< span  class="hljs-name">init-param> 
             < span  class="hljs-tag"><< span  class="hljs-name">param-name>log4j-properties-location< span  class="hljs-tag"></< span  class="hljs-name">param-name> 
             < span  class="hljs-tag"><< span  class="hljs-name">param-value>/WEB-INF/classes/log4j.properties< span  class="hljs-tag"></< span  class="hljs-name">param-value> 
         < span  class="hljs-tag"></< span  class="hljs-name">init-param> 
         < span  class="hljs-tag"><< span  class="hljs-name">load-on-startup>1< span  class="hljs-tag"></< span  class="hljs-name">load-on-startup> 
     < span  class="hljs-tag"></< span  class="hljs-name">servlet> 
 
     < span  class="hljs-tag"><< span  class="hljs-name">servlet-mapping> 
         < span  class="hljs-tag"><< span  class="hljs-name">servlet-name>Log4JTestServlet< span  class="hljs-tag"></< span  class="hljs-name">servlet-name> 
         < span  class="hljs-tag"><< span  class="hljs-name">url-pattern>/test< span  class="hljs-tag"></< span  class="hljs-name">url-pattern> 
     < span  class="hljs-tag"></< span  class="hljs-name">servlet-mapping> 
 
< span  class="hljs-tag"></< span  class="hljs-name">web-app></ span ></ span ></ span ></ span ></ span ></ span ></ span ></ span ></ span ></ span ></ span ></ span ></ span ></ span ></ span ></ span ></ span ></ span ></ span ></ span ></ span ></ span ></ span ></ span ></ span ></ span ></ span ></ span ></ span ></ span ></ span ></ span ></ span ></ span ></ span ></ span ></ span ></ span ></ span ></ span ></ span ></ span ></ span ></ span ></ span ></ span ></ span ></ span ></ span ></ span ></ span ></ span ></ span ></ span ></ span ></ span ></ span ></ span ></ span ></ span ></ span ></ span ></ span ></ span ></ span ></ span ></ span ></ span ></ span ></ span ></ span ></ span ></ span ></ span ></ span ></ span >

(3)配置文件log4j.properties

<span class= "hljs-comment" > ### set log levels ### 
<span class= "hljs-built_in" >log4j.rootLogger = debug,stdout,D,E 
 
<span class= "hljs-built_in" >log4j.appender.stdout = org.apache.log4j.ConsoleAppender 
<span class= "hljs-built_in" >log4j.appender.stdout.Target = System.out 
<span class= "hljs-built_in" >log4j.appender.stdout.layout = org.apache.log4j.PatternLayout 
<span class= "hljs-built_in" >log4j.appender.stdout.layout.ConversionPattern = [%-5p] %d{yyyy-MM- dd  HH:mm:ss,SSS} method:%l%n%m%n 
 
<span class= "hljs-built_in" >log4j.appender.D = org.apache.log4j.DailyRollingFileAppender 
<span class= "hljs-built_in" >log4j.appender.D.File = F: //logs/log .log 
<span class= "hljs-built_in" >log4j.appender.D.Append = <span class= "hljs-literal" > true 
<span class= "hljs-built_in" >log4j.appender.D.Threshold = DEBUG  
<span class= "hljs-built_in" >log4j.appender.D.layout = org.apache.log4j.PatternLayout 
<span class= "hljs-built_in" >log4j.appender.D.layout.ConversionPattern = %<span class= "hljs-_" >-d{yyyy-MM- dd  HH:mm:ss}  [ %t:%r ] - [ %p ]  %m%n 
 
<span class= "hljs-built_in" >log4j.appender.E = org.apache.log4j.DailyRollingFileAppender 
<span class= "hljs-built_in" >log4j.appender.E.File =F: //logs/error .log  
<span class= "hljs-built_in" >log4j.appender.E.Append = <span class= "hljs-literal" > true 
<span class= "hljs-built_in" >log4j.appender.E.Threshold = ERROR  
<span class= "hljs-built_in" >log4j.appender.E.layout = org.apache.log4j.PatternLayout 
<span class= "hljs-built_in" >log4j.appender.E.layout.ConversionPattern = %<span class= "hljs-_" >-d{yyyy-MM- dd  HH:mm:ss}  [ %t:%r ] - [ %p ]  %m%n< /span >< /span >< /span >< /span >< /span >< /span >< /span >< /span >< /span >< /span >< /span >< /span >< /span >< /span >< /span >< /span >< /span >< /span >< /span >< /span >< /span >< /span >

(4)web容器一来就初始化的servlet

Log4JInitServlet.java

package  com.mucfc; 
 
<span class = "hljs-keyword" > import  java.io.File; 
<span class = "hljs-keyword" > import  java.io.IOException; 
 
<span class = "hljs-keyword" > import  javax.servlet.ServletConfig; 
<span class = "hljs-keyword" > import  javax.servlet.ServletContext; 
<span class = "hljs-keyword" > import  javax.servlet.ServletException; 
<span class = "hljs-keyword" > import  javax.servlet.annotation.WebServlet; 
<span class = "hljs-keyword" > import  javax.servlet.http.HttpServlet; 
<span class = "hljs-keyword" > import  javax.servlet.http.HttpServletRequest; 
<span class = "hljs-keyword" > import  javax.servlet.http.HttpServletResponse; 
 
<span class = "hljs-keyword" > import  org.apache.log4j.BasicConfigurator; 
<span class = "hljs-keyword" > import  org.apache.log4j.PropertyConfigurator; 
 
<span class = "hljs-comment" > /**
  * Servlet implementation class Log4JInitServlet
  */ 
@<span class = "hljs-type" >WebServlet(<span class = "hljs-string" > "/Log4JInitServlet"
<span class = "hljs-keyword" > public  <span class = "hljs-class" ><span class = "hljs-keyword" > class  <span class = "hljs-title" >Log4JInitServlet <span class = "hljs-title" > extends  <span class = "hljs-title" >HttpServlet { 
     <span class = "hljs-keyword" > private  <span class = "hljs-keyword" > static  <span class = "hljs-keyword" > final  long  serialVersionUID = 1L; 
 
     <span class = "hljs-comment" > /**
      * @see HttpServlet#HttpServlet()
      */ 
     <span class = "hljs-keyword" > public  <span class = "hljs-type" >Log4JInitServlet() { 
         <span class = "hljs-keyword" > super (); 
         <span class = "hljs-comment" > // TODO Auto-generated constructor stub 
    
 
     <span class = "hljs-comment" > /**
      * @see Servlet#init(ServletConfig)
      */ 
     <span class = "hljs-keyword" > public  void  <span class = "hljs-keyword" >init(<span class = "hljs-type" >ServletConfig config) <span class = "hljs-keyword" > throws  <span class = "hljs-type" >ServletException { 
         <span class = "hljs-type" >System.out.<span class = "hljs-built_in" >println(<span class = "hljs-string" > "Log4JInitServlet 正在初始化 log4j日志设置信息" ); 
         <span class = "hljs-type" >String log4jLocation = config.getInitParameter(<span class = "hljs-string" > "log4j-properties-location" ); 
 
         <span class = "hljs-type" >ServletContext sc = config.getServletContext(); 
 
         <span class = "hljs-keyword" > if  (log4jLocation == null ) { 
             <span class = "hljs-type" >System.err.<span class = "hljs-built_in" >println(<span class = "hljs-string" > "*** 没有 log4j-properties-location 初始化的文件, 所以使用 BasicConfigurator初始化" ); 
             <span class = "hljs-type" >BasicConfigurator.configure(); 
         } <span class = "hljs-keyword" > else 
             <span class = "hljs-type" >String webAppPath = sc.getRealPath(<span class = "hljs-string" > "/" ); 
             <span class = "hljs-type" >String log4jProp = webAppPath + log4jLocation; 
             <span class = "hljs-type" >File yoMamaYesThisSaysYoMama = new  <span class = "hljs-type" >File(log4jProp); 
             <span class = "hljs-keyword" > if  (yoMamaYesThisSaysYoMama.exists()) { 
                 <span class = "hljs-type" >System.out.<span class = "hljs-built_in" >println(<span class = "hljs-string" > "使用: "  + log4jProp+<span class = "hljs-string" > "初始化日志设置信息" ); 
                 <span class = "hljs-type" >PropertyConfigurator.configure(log4jProp); 
             } <span class = "hljs-keyword" > else 
                 <span class = "hljs-type" >System.err.<span class = "hljs-built_in" >println(<span class = "hljs-string" > "*** " + log4jProp + <span class = "hljs-string" > " 文件没有找到, 所以使用 BasicConfigurator初始化" ); 
                 <span class = "hljs-type" >BasicConfigurator.configure(); 
            
        
         <span class = "hljs-keyword" > super .<span class = "hljs-keyword" >init(config); 
    
 
     <span class = "hljs-comment" > /**
      * @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse response)
      */ 
     protected  void  doGet(<span class = "hljs-type" >HttpServletRequest request, <span class = "hljs-type" >HttpServletResponse response) <span class = "hljs-keyword" > throws  <span class = "hljs-type" >ServletException, <span class = "hljs-type" >IOException { 
         <span class = "hljs-comment" > // TODO Auto-generated method stub 
    
 
     <span class = "hljs-comment" > /**
      * @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse response)
      */ 
     protected  void  doPost(<span class = "hljs-type" >HttpServletRequest request, <span class = "hljs-type" >HttpServletResponse response) <span class = "hljs-keyword" > throws  <span class = "hljs-type" >ServletException, <span class = "hljs-type" >IOException { 
         <span class = "hljs-comment" > // TODO Auto-generated method stub 
    
 
}</span></span></span></span></span></span></span></span></span></span></span></span></span></span></span></span></span></span></span></span></span></span></span></span></span></span></span></span></span></span></span></span></span></span></span></span></span></span></span></span></span></span></span></span></span></span></span></span></span></span></span></span></span></span></span></span></span></span></span></span></span></span></span></span></span></span></span></span></span></span></span></span></span></span></span></span></span></span></span>

调用日志Log4JTestServlet,java

<span class = "hljs-keyword" > package  com.mucfc; 
 
<span class = "hljs-keyword" > import  java.io.IOException; 
 
<span class = "hljs-keyword" > import  javax.servlet.ServletConfig; 
<span class = "hljs-keyword" > import  javax.servlet.ServletException; 
<span class = "hljs-keyword" > import  javax.servlet.annotation.WebServlet; 
<span class = "hljs-keyword" > import  javax.servlet.http.HttpServlet; 
<span class = "hljs-keyword" > import  javax.servlet.http.HttpServletRequest; 
<span class = "hljs-keyword" > import  javax.servlet.http.HttpServletResponse; 
 
<span class = "hljs-keyword" > import  org.apache.log4j.Logger; 
 
<span class = "hljs-comment" > /**
  * Servlet implementation class Log4JTestServlet
  */ 
<span class = "hljs-meta" > @WebServlet (<span class = "hljs-string" > "/Log4JTestServlet"
<span class = "hljs-keyword" > public  <span class = "hljs-class" ><span class = "hljs-keyword" > class  <span class = "hljs-title" >Log4JTestServlet <span class = "hljs-keyword" > extends  <span class = "hljs-title" >HttpServlet { 
     <span class = "hljs-keyword" > private  <span class = "hljs-keyword" > static  <span class = "hljs-keyword" > final  <span class = "hljs-keyword" > long  serialVersionUID = <span class = "hljs-number" >1L; 
     <span class = "hljs-keyword" > private  <span class = "hljs-keyword" > static  Logger logger = Logger.getLogger(Log4JTestServlet. class );   
 
     <span class = "hljs-comment" > /**
      * <span class="hljs-doctag">@see HttpServlet#HttpServlet()
      */ 
     <span class = "hljs-function" ><span class = "hljs-keyword" > public  <span class = "hljs-title" >Log4JTestServlet<span class = "hljs-params" >() { 
         <span class = "hljs-keyword" > super (); 
         <span class = "hljs-comment" > // TODO Auto-generated constructor stub 
    
 
     <span class = "hljs-comment" > /**
      * <span class="hljs-doctag">@see Servlet#init(ServletConfig)
      */ 
     <span class = "hljs-function" ><span class = "hljs-keyword" > public  <span class = "hljs-keyword" > void  <span class = "hljs-title" >init<span class = "hljs-params" >(ServletConfig config) <span class = "hljs-keyword" > throws  ServletException { 
         <span class = "hljs-comment" > // TODO Auto-generated method stub 
    
 
     <span class = "hljs-comment" > /**
      * <span class="hljs-doctag">@see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse response)
      */ 
     <span class = "hljs-function" ><span class = "hljs-keyword" > protected  <span class = "hljs-keyword" > void  <span class = "hljs-title" >doGet<span class = "hljs-params" >(HttpServletRequest request, HttpServletResponse response) <span class = "hljs-keyword" > throws  ServletException, IOException { 
         <span class = "hljs-comment" > // 记录debug级别的信息   
         logger.debug(<span class = "hljs-string" > "This is debug message." );   
         <span class = "hljs-comment" > // 记录info级别的信息   
         logger.info(<span class = "hljs-string" > "This is info message." );   
         <span class = "hljs-comment" > // 记录error级别的信息   
         logger.error(<span class = "hljs-string" > "This is error message." );   
    
 
     <span class = "hljs-comment" > /**
      * <span class="hljs-doctag">@see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse response)
      */ 
     <span class = "hljs-function" ><span class = "hljs-keyword" > protected  <span class = "hljs-keyword" > void  <span class = "hljs-title" >doPost<span class = "hljs-params" >(HttpServletRequest request, HttpServletResponse response) <span class = "hljs-keyword" > throws  ServletException, IOException { 
         doGet(request,response); 
    
 
}</span></span></span></span></span></span></span></span></span></span></span></span></span></span></span></span></span></span></span></span></span></span></span></span></span></span></span></span></span></span></span></span></span></span></span></span></span></span></span></span></span></span></span></span></span></span></span></span></span></span></span></span></span></span></span></span></span></span></span></span></span></span></span></span>

接下来就是运行了,来看看结果:

输出结果:

四、Spring中使用Log4j

这里要实现web项目中利用Spring来使用Log4j

(1)接上面的工程,然后再导入Spring的包

(2)web.xml增加

< span  class="hljs-comment"> <!-- 设置根目录 --> 
    < span  class="hljs-tag"><< span  class="hljs-name">context-param>   
        < span  class="hljs-tag"><< span  class="hljs-name">param-name>webAppRootKey< span  class="hljs-tag"></< span  class="hljs-name">param-name>   
        < span  class="hljs-tag"><< span  class="hljs-name">param-value>webapp.root< span  class="hljs-tag"></< span  class="hljs-name">param-value>   
    < span  class="hljs-tag"></< span  class="hljs-name">context-param>   
 
    < span  class="hljs-tag"><< span  class="hljs-name">context-param> 
     < span  class="hljs-tag"><< span  class="hljs-name">param-name>log4jConfigLocation< span  class="hljs-tag"></< span  class="hljs-name">param-name> 
     < span  class="hljs-tag"><< span  class="hljs-name">param-value>/WEB-INF/classes/log4j.properties< span  class="hljs-tag"></< span  class="hljs-name">param-value> 
< span  class="hljs-tag"></< span  class="hljs-name">context-param> 
< span  class="hljs-comment"> <!-- 3000表示 开一条watchdog线程每60秒扫描一下配置文件的变化;这样便于日志存放位置的改变 --> 
< span  class="hljs-tag"><< span  class="hljs-name">context-param>   
         < span  class="hljs-tag"><< span  class="hljs-name">param-name>log4jRefreshInterval< span  class="hljs-tag"></< span  class="hljs-name">param-name>   
         < span  class="hljs-tag"><< span  class="hljs-name">param-value>3000< span  class="hljs-tag"></< span  class="hljs-name">param-value>   
    < span  class="hljs-tag"></< span  class="hljs-name">context-param>  
< span  class="hljs-tag"><< span  class="hljs-name">listener> 
     < span  class="hljs-tag"><< span  class="hljs-name">listener-class>org.springframework.web.util.Log4jConfigListener< span  class="hljs-tag"></< span  class="hljs-name">listener-class> 
< span  class="hljs-tag"></< span  class="hljs-name">listener></ span ></ span ></ span ></ span ></ span ></ span ></ span ></ span ></ span ></ span ></ span ></ span ></ span ></ span ></ span ></ span ></ span ></ span ></ span ></ span ></ span ></ span ></ span ></ span ></ span ></ span ></ span ></ span ></ span ></ span ></ span ></ span ></ span ></ span ></ span ></ span ></ span ></ span ></ span ></ span ></ span ></ span ></ span ></ span ></ span ></ span >

整个内容如下:

< span  class="php">< span  class="hljs-meta"><? xml  version=<span class="hljs-string">"1.0" encoding=< span  class="hljs-string">"UTF-8"< span  class="hljs-meta">?> 
< span  class="hljs-tag"><< span  class="hljs-name">web-app < span  class="hljs-attr">xmlns:xsi=< span  class="hljs-string">"http://www.w3.org/2001/XMLSchema-instance" 
     < span  class="hljs-attr">xmlns=< span  class="hljs-string">"http://java.sun.com/xml/ns/javaee" 
     < span  class="hljs-attr">xsi:schemaLocation=< span  class="hljs-string">"http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_3_0.xsd" 
     < span  class="hljs-attr">id=< span  class="hljs-string">"WebApp_ID" < span  class="hljs-attr">version=< span  class="hljs-string">"3.0"> 
     < span  class="hljs-tag"><< span  class="hljs-name">display-name>LogLearning< span  class="hljs-tag"></< span  class="hljs-name">display-name> 
 
     < span  class="hljs-tag"><< span  class="hljs-name">servlet> 
         < span  class="hljs-tag"><< span  class="hljs-name">servlet-name>Log4JTestServlet< span  class="hljs-tag"></< span  class="hljs-name">servlet-name> 
         < span  class="hljs-tag"><< span  class="hljs-name">servlet-class>com.mucfc.Log4JTestServlet< span  class="hljs-tag"></< span  class="hljs-name">servlet-class> 
     < span  class="hljs-tag"></< span  class="hljs-name">servlet> 
 
     < span  class="hljs-comment"> <!--用来启动 log4jConfigLocation的servlet --> 
< span  class="hljs-comment"> <!--     <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>--> 
 
     < span  class="hljs-tag"><< span  class="hljs-name">servlet-mapping> 
         < span  class="hljs-tag"><< span  class="hljs-name">servlet-name>Log4JTestServlet< span  class="hljs-tag"></< span  class="hljs-name">servlet-name> 
         < span  class="hljs-tag"><< span  class="hljs-name">url-pattern>/test< span  class="hljs-tag"></< span  class="hljs-name">url-pattern> 
     < span  class="hljs-tag"></< span  class="hljs-name">servlet-mapping>  
 
         < span  class="hljs-comment"> <!-- Spring 容器加载 --> 
     < span  class="hljs-tag"><< span  class="hljs-name">listener> 
         < span  class="hljs-tag"><< span  class="hljs-name">listener-class>org.springframework.web.context.ContextLoaderListener< span  class="hljs-tag"></< span  class="hljs-name">listener-class> 
     < span  class="hljs-tag"></< span  class="hljs-name">listener> 
     < span  class="hljs-tag"><< span  class="hljs-name">context-param> 
         < span  class="hljs-tag"><< span  class="hljs-name">param-name>contextConfigLocation< span  class="hljs-tag"></< span  class="hljs-name">param-name> 
         < span  class="hljs-tag"><< span  class="hljs-name">param-value>classpath:applicationContext.xml< span  class="hljs-tag"></< span  class="hljs-name">param-value> 
     < span  class="hljs-tag"></< span  class="hljs-name">context-param>  
 
     < span  class="hljs-comment"> <!-- 设置根目录 --> 
     < span  class="hljs-tag"><< span  class="hljs-name">context-param>   
         < span  class="hljs-tag"><< span  class="hljs-name">param-name>webAppRootKey< span  class="hljs-tag"></< span  class="hljs-name">param-name>   
         < span  class="hljs-tag"><< span  class="hljs-name">param-value>webapp.root< span  class="hljs-tag"></< span  class="hljs-name">param-value>   
     < span  class="hljs-tag"></< span  class="hljs-name">context-param>   
 
     < span  class="hljs-tag"><< span  class="hljs-name">context-param> 
         < span  class="hljs-tag"><< span  class="hljs-name">param-name>log4jConfigLocation< span  class="hljs-tag"></< span  class="hljs-name">param-name> 
         < span  class="hljs-tag"><< span  class="hljs-name">param-value>/WEB-INF/classes/log4j.properties< span  class="hljs-tag"></< span  class="hljs-name">param-value> 
     < span  class="hljs-tag"></< span  class="hljs-name">context-param> 
     < span  class="hljs-comment"> <!-- 3000表示 开一条watchdog线程每60秒扫描一下配置文件的变化;这样便于日志存放位置的改变 --> 
     < span  class="hljs-tag"><< span  class="hljs-name">context-param>   
          < span  class="hljs-tag"><< span  class="hljs-name">param-name>log4jRefreshInterval< span  class="hljs-tag"></< span  class="hljs-name">param-name>   
          < span  class="hljs-tag"><< span  class="hljs-name">param-value>3000< span  class="hljs-tag"></< span  class="hljs-name">param-value>