1. 程式人生 > >java Web應用配置log4j日誌記錄

java Web應用配置log4j日誌記錄

第一步:首先建立一個WEB工程,去log4j官網下log4j的JAR包匯入到工程的lib目錄下

第二步:在src目錄下建一個log4j.properties 檔案,檔案命名可以由自己,只是記載入時候和這裡名字一致就行;

log4j.properties  裡邊的內容如下:

 ### set log levels ###
log4j.rootLogger = debug,stdout,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 =  %d{ABSOLUTE} %5p %c{1}:%L - %m%n

log4j.appender.E= org.apache.log4j.DailyRollingFileAppender
log4j.appender.E.File =${catalina.home}/logs/log_
log4j.appender.E.DatePattern=yyyy-MM-dd'.log'
log4j.appender.E.Threshold =DEBUG
log4j.appender.E.layout = org.apache.log4j.PatternLayout
log4j.appender.E.layout.ConversionPattern =%-d{yyyy-MM-dd HH\:mm\:ss}[%c] [%t\:%r] - [%p]  %m%n

可以單指定日誌輸出到某個檔案:

log4j.logger.pay-log=Info,pay-loglog4j.appender.pay-log=org.apache.log4j.DailyRollingFileAppender  log4j.appender.pay-log.File=D:/logs/pay-log.loglog4j.appender.pay-log.DatePattern='.'yyyy-MM-ddlog4j.appender.pay-log.Threshold =DEBUGlog4j.appender.pay-log.layout=org.apache.log4j.PatternLayout  log4j.appender.pay-log.layout.ConversionPattern =%-d{yyyy-MM-dd HH\:mm\:ss}[%c] [%t\:%r] - [%p]  %m%n



解釋下幾個常用的,其它的在詳細的,請自己去網上查詢資料:
log4j.rootLogger = debug,stdout,E  意思是父類logger 會以比debug 級別高的日誌輸出到 stdout,E 兩個地方,子類也一樣
stdout是一個日誌記錄配置,它的意思是把日誌輸出到控制檯上,也就是這個配置屬性--->log4j.appender.stdout.Target = System.out ,到時候到了生產上可以註解掉就可以了。
E是一個日誌記錄配置,它是把日誌檔案記錄到檔案中去,log4j.appender.E.File =${catalina.home}/logs/log_  是放日誌檔案的路徑,其中${catalina.home}是容器的路徑
log4j.appender.E= org.apache.log4j.DailyRollingFileAppender  這個屬性配置是一天產生一個新的日誌檔案(還有其它配置方式,這個是用的最多的)
log4j.appender.E.DatePattern=yyyy-MM-dd'.log'  這個屬性是以時間為名字的檔案日誌,形式如下:
log_2011-06-26.log,log_2011-06-28.log,不過第一個生成的日誌檔案的名字是:log_
log4j.appender.E.layout.ConversionPattern =%-d{yyyy-MM-dd HH\:mm\:ss}[%c] [%t\:%r] - [%p]  %m%n  這個是輸出日誌內容格式,詳細情況請自己查閱資料;
log4j.appender.E.Threshold =DEBUG  這個是輸出日誌級別(意思是隻輸出比DEBUG級別高的日誌資訊);

#appender名字定義
log4j.rootLogger=INFO,FILE,consoleAppender,RollingFile,MAIL,DailyRollingFile,DATABASE
log4j.addivity.org.apache=true

#配置日誌資訊輸出目的地
#log4j.appender.appenderName = fully.qualified.name.of.appender.class
#(如:log4j.appender.RollingFile = org.apache.log4j.RollingFileAppender)
# 1.org.apache.log4j.ConsoleAppender(控制檯)
# 2.org.apache.log4j.FileAppender(檔案)
# 3.org.apache.log4j.DailyRollingFileAppender(每天產生一個日誌檔案)
# 4.org.apache.log4j.RollingFileAppender(檔案大小到達指定尺寸的時候產生一個新的檔案)
# 5.org.apache.log4j.WriterAppender(將日誌資訊以流格式傳送到任意指定的地方)

#配置日誌資訊的格式
#log4j.appender.appenderName.layout = fully.qualified.name.of.layout.class
#(如:log4j.appender.RollingFile.layout = org.apache.log4j.HTMLLayout)
# 1.org.apache.log4j.HTMLLayout(以HTML表格形式佈局),
# 2.org.apache.log4j.PatternLayout(可以靈活地指定佈局模式),
# 3.org.apache.log4j.SimpleLayout(包含日誌資訊的級別和資訊字串),
# 4.org.apache.log4j.TTCCLayout(包含日誌產生的時間、執行緒、類別等等資訊)

#日記記錄的優先順序:priority,優先順序由高到低分為 
# OFF ,FATAL ,ERROR ,WARN ,INFO ,DEBUG ,ALL。
# Log4j建議只使用FATAL ,ERROR ,WARN ,INFO ,DEBUG這五個級別。
# ERROR 為嚴重錯誤 主要是程式的錯誤
# WARN 為一般警告,比如session丟失
# INFO 為一般要顯示的資訊,比如登入登出
# DEBUG 為程式的除錯資訊


#輸出格式:layout中的引數都以%開始,後面不同的引數代表不同的格式化資訊(引數按字母表順序列出):
# %c 輸出所屬類的全名,可在修改為 %d{Num} ,Num類名輸出的維(如:"org.apache.elathen.ClassName",%C{2}將輸出elathen.ClassName)
# %d 輸出日誌時間其格式為 %d{yyyy-MM-dd HH:mm:ss,SSS},可指定格式 如 %d{HH:mm:ss}
# %l 輸出日誌事件發生位置,包括類目名、發生執行緒,在程式碼中的行數
# %n 換行符
# %m 輸出程式碼指定資訊,如info(“message”),輸出message
# %p 輸出優先順序,即 FATAL ,ERROR 等
# %r 輸出從啟動到顯示該log資訊所耗費的毫秒數
# %t 輸出產生該日誌事件的執行緒名


#ConsoleAppender,控制檯輸出
#FileAppender,檔案日誌輸出
#SMTPAppender,發郵件輸出日誌
#SocketAppender,Socket日誌
#NTEventLogAppender,Window NT日誌
#SyslogAppender,
#JMSAppender,
#AsyncAppender,
#NullAppender



第三步:配置容器起動時候載入log4j配置檔案:
建立一個servlet內容如下:

package com.tchzt.logTest;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;

import org.apache.log4j.PropertyConfigurator;

public class Log4jInit extends HttpServlet {
 private static final long serialVersionUID = 1L;
 public void destroy() {
  super.destroy();
 }

 public Log4jInit() {
  super();
 }

 /**
  * Initialization of the servlet. <br>
  *
  * @throws ServletException if an error occurs
  */
 public void init() throws ServletException {
  String file =this.getInitParameter("log4j");//從web.xml配置讀取,名字一定要和web.xml配置一致
  if(file != null){
     PropertyConfigurator.configure(file);
  }
 }

}

web.xml配置:
<servlet>
  <servlet-name>Log4jInit</servlet-name>
  <servlet-class>com.tchzt.logTest.Log4jInit</servlet-class>
  <init-param>
   <param-name>log4j</param-name>//這個是名字是下邊路徑配置的標識(好像KEY一樣)
   <param-value>/WEB-INF/classes/log4j.properties</param-value>//這是容器初始化時候載入log4j配置檔案的路徑(這好像一個value);
  </init-param>
 </servlet>

好了基本上配置完了開始下測試了:
測試類:建立一個servlet內容如下:

package com.tchzt.logTest;

import java.io.IOException;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.log4j.Logger;

public class Test extends HttpServlet {

 private static final long serialVersionUID = 1L;

 /**
  * The doGet method of the servlet. <br>
  *
  * This method is called when a form has its tag value method equals to get.
  * 
  * @param request the request send by the client to the server
  * @param response the response send by the server to the client
  * @throws ServletException if an error occurred
  * @throws IOException if an error occurred
  */
 public void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
    //如果直接 className.class 日誌輸出到全域性的 即rootLogger 指定的檔案中
    Logger logger = Logger.getLogger(Test.class.getName());
   //如果指定logger名字,則是把日誌,輸出到pay-log 指定的日誌檔案中去
   Logger logger = Logger.getLogger(“pay-log”);
  MyLog4j.getSomething();
  System.out.println("================97987==============");
  logger.info("日誌資訊開始!");
  logger.info("日誌資訊結束!");
  try {
   Integer.parseInt("a");
  } catch (NumberFormatException e) {
   logger.error("解析數字出現異常",e);
   e.printStackTrace();
  }
 }

 /**
  * The doPost method of the servlet. <br>
  *
  * This method is called when a form has its tag value method equals to post.
  * 
  * @param request the request send by the client to the server
  * @param response the response send by the server to the client
  * @throws ServletException if an error occurred
  * @throws IOException if an error occurred
  */
 public void doPost(HttpServletRequest request, HttpServletResponse response)throws ServletException, IOException {
  this.doGet(request, response);
 }

}


這個servlet 的web.xml配置如下:
<servlet>
    <servlet-name>Test</servlet-name>
    <servlet-class>com.tchzt.logTest.Test</servlet-class>
  </servlet>

  <servlet-mapping>
    <servlet-name>Test</servlet-name>
    <url-pattern>/servlet/Test</url-pattern>
  </servlet-mapping>


啟動容器:輸出URL:http://localhost:8080/Log4jWebTest/servlet/Test
第二次關閉容器,修改系統時間;在啟動容器,最後生成日誌檔案如下:

log_;log_2011-06-26.log;log_2011-06-28.log;log_2011-06-30.log

內容這裡選一個檔案裡的內容:
2011-06-30 21:59:28[test.jsp] [http-8080-2:0] - [ERROR]  asdfasdf
2011-06-30 21:59:28[test.jsp] [http-8080-2:16] - [INFO]  Test Logging in JSP
2011-06-30 21:59:28[test.jsp] [http-8080-2:16] - [FATAL]  Test fatal logging in jsp page.
2011-06-30 21:59:28[test.jsp] [http-8080-2:16] - [ERROR]  解析數字出現異常
java.lang.NumberFormatException: For input string: "a"
 at java.lang.NumberFormatException.forInputString(Unknown Source)
 at java.lang.Integer.parseInt(Unknown Source)
 at java.lang.Integer.parseInt(Unknown Source)
 at org.apache.jsp.index_jsp._jspService(index_jsp.java:90)
 at org.apache.jasper.runtime.HttpJspBase.service(HttpJspBase.java:70)
 at javax.servlet.http.HttpServlet.service(HttpServlet.java:803)
 at org.apache.jasper.servlet.JspServletWrapper.service(JspServletWrapper.java:393)
 at org.apache.jasper.servlet.JspServlet.serviceJspFile(JspServlet.java:320)
 at org.apache.jasper.servlet.JspServlet.service(JspServlet.java:266)
 at javax.servlet.http.HttpServlet.service(HttpServlet.java:803)
 at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:290)
 at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:206)
 at org.apache.catalina.core.StandardWrapperValve.invoke(StandardWrapperValve.java:233)
 at org.apache.catalina.core.StandardContextValve.invoke(StandardContextValve.java:175)
 at org.apache.catalina.core.StandardHostValve.invoke(StandardHostValve.java:128)
 at org.apache.catalina.valves.ErrorReportValve.invoke(ErrorReportValve.java:102)
 at org.apache.catalina.core.StandardEngineValve.invoke(StandardEngineValve.java:109)
 at org.apache.catalina.connector.CoyoteAdapter.service(CoyoteAdapter.java:263)
 at org.apache.coyote.http11.Http11Processor.process(Http11Processor.java:844)
 at org.apache.coyote.http11.Http11Protocol$Http11ConnectionHandler.process(Http11Protocol.java:584)
 at org.apache.tomcat.util.net.JIoEndpoint$Worker.run(JIoEndpoint.java:447)
 at java.lang.Thread.run(Unknown Source)
2011-06-30 21:59:37[com.tchzt.logTest.MyLog4j] [http-8080-2:8641] - [ERROR]  java.io.FileNotFoundException: F:\tt.txt (系統找不到指定的檔案。)
2011-06-30 21:59:37[com.tchzt.logTest.Test] [http-8080-2:8656] - [INFO]  日誌資訊開始!
2011-06-30 21:59:37[com.tchzt.logTest.Test] [http-8080-2:8656] - [INFO]  日誌資訊結束!
2011-06-30 21:59:37[com.tchzt.logTest.Test] [http-8080-2:8656] - [ERROR]  解析數字出現異常
java.lang.NumberFormatException: For input string: "a"
 at java.lang.NumberFormatException.forInputString(Unknown Source)
 at java.lang.Integer.parseInt(Unknown Source)
 at java.lang.Integer.parseInt(Unknown Source)
 at com.tchzt.logTest.Test.doGet(Test.java:33)
 at javax.servlet.http.HttpServlet.service(HttpServlet.java:690)
 at javax.servlet.http.HttpServlet.service(HttpServlet.java:803)
 at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:290)
 at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:206)
 at org.apache.catalina.core.StandardWrapperValve.invoke(StandardWrapperValve.java:233)
 at org.apache.catalina.core.StandardContextValve.invoke(StandardContextValve.java:175)
 at org.apache.catalina.core.StandardHostValve.invoke(StandardHostValve.java:128)
 at org.apache.catalina.valves.ErrorReportValve.invoke(ErrorReportValve.java:102)
 at org.apache.catalina.core.StandardEngineValve.invoke(StandardEngineValve.java:109)
 at org.apache.catalina.connector.CoyoteAdapter.service(CoyoteAdapter.java:263)
 at org.apache.coyote.http11.Http11Processor.process(Http11Processor.java:844)
 at org.apache.coyote.http11.Http11Protocol$Http11ConnectionHandler.process(Http11Protocol.java:584)
 at org.apache.tomcat.util.net.JIoEndpoint$Worker.run(JIoEndpoint.java:447)

 at java.lang.Thread.run(Unknown Source)