Log4J是Apache的一個開放源代碼項目(http://logging.apache.org/log4j/docs/),它是一個日誌操做包。經過使用Log4J,能夠指定日誌信息輸出的目的地,控制每一條日誌的輸出格式,定義日誌信息的級別。全部這些功能經過一個配置文件靈活進行配置。html
1、LOG4J組成java
LOG4J主要由三大組件組成:
. Logger: 決定什麼日誌信息應該被輸出、什麼日誌信息應該被忽略;
. Appender: 指定日誌信息應該輸出到什麼地方, 這些地方能夠是控制檯、文件、網絡設備;
. Layout: 指定日誌信息的輸出格式;web
一個Logger能夠有多個Appender,也就是說日誌信息能夠同時輸出到多個設備上,每一個Appender對應
一種Layout(示例見下圖)。spring
↗ Appender1 → Layout
/
Logger
﹨
↘ Appender2 → Layoutsql
2、Logger組件apache
1. Logger組件提供的方法:服務器
Logger組件是LOG4J的核心組件,它表明了Log4J的日誌記錄器,它可以對日誌信息進行分類篩選。它由org.apache.log4j.Logger類實現,提供了以下方法:網絡
java 代碼session
1. package org.apache.log4j;
2.
3. public class Logger {
4.
5. // Creation & retrieval methods:
6. public static Logger getRootLogger();
7. public static Logger getLogger(String name);
8.
9. // printing methods:
10. public void debug(Object message);
11. public void info(Object message);
12. public void warn(Object message);
13. public void error(Object message);
14. public void fatal(Object message);
15.
16. // generic printing method:
17. public void log(Priority p, Object message);
18. } app
2. 在配置文件中配置Logger組件
可在Log4J配置文件中配置本身的Logger組件,示例:
log4j.logger.myLogger=WARN
以上代碼定義了一個Logger組件,名稱爲myLogger,日誌級別爲WARN。
3. 日誌級別種類:
一共有五種,級別由高到低依次是:fatal、error、warn、info、debug。得到Logger實例後,咱們可調用如下方法之一輸出日誌信息:
public void debug(Object message); //輸出debug級別的日誌信息;
public void info(Object message); //輸出info級別的日誌信息;
public void warn(Object message); //輸出warn級別的日誌信息;
public void error(Object message); //輸出error級別的日誌信息;
public void fatal(Object message); //輸出fatal級別的日誌信息;
public void log(Priority p, Object message);//輸出參數Priority指定級別的日誌信息;
以上方法只有當它的級別大於或等於Logger組件配置的日誌級別時才調用。之前面咱們配置的myLogger爲例,它的日誌級別爲WARN, 那麼在程序中,它的warn()、error()、fatal()方法會被執行。對於log()方法,只有當它的參數Priority指定的日誌級別大於或等於WARN時,它纔會被執行。
4. 爲何須要對日誌進行分級?
在寫程序的時候,爲了調試程序,咱們會在不少出錯的地方輸出大量的日誌信息。當程序調試完,不須要這些信息時,將程序中這些輸出日誌信息代碼刪除嗎?這樣費時費力,對於大型程序幾乎不可行。經過對日誌分級,假如不想輸出WARN級別的日誌信息,則Logger組件的級別調高便可,省時省心。
5. Logger組件的繼承性
Log4J提供了一個root Logger,它是全部Logger組件的「祖先」,它永遠存在,且不能經過名字檢索或引用,經過Logger.getRootLogger()方法取得它。配置root Logger代碼:
log4j.rootLogger=INFO,console
可在配置文件中方便地配置存在繼承關係的Logger組件,凡是在符號「.」後面的組件都會成爲在符號「.」前面的Logger組件的子類。例如:
log4j.apache.myLogger=WARN
log4j.apache.myLogger.mySonLogger=,file
以上代碼中, mySonLogger是myLogger的子類Logger組件。Logger組件的繼承關係:
. 若是子類Logger組件沒有定義日誌級別,則將繼承父類的日誌級別;
. 若是子類Logger組件定義了日誌級別,就不會繼承父類的日誌級別;
. 默認狀況下,子類Logger組件會繼承父類全部的Appender,把它們加入到本身的Appener;
. 若是把子類Logger組件的additivity標誌設爲false,那麼它就不會繼承父類Appender。additivity標誌 默認值爲false;
以上配置的三個Logger繼承關係示例如圖:
root Logger: 日誌級別=INFO appender清單=console
↑
myLogger: 日誌級別=WARN appender清單=null
↑
mySonLogger: 日誌級別=null appender清單=file
這三個Logger組件實際日誌級別和Appender以下表:
Logger組件 日誌級別 Appender清單
root Logger INFO console
myLogger WARN console(繼承)
mySonLogger WARN(繼承) file,console(繼承)
3、Appender組件
Appender組件決定將日誌信息輸出到什麼地方。支持如下目的地:
. 控制檯(Console);
. 文件(File);
. GUI組件(GUI component);
. 套接口服務器(Remote socket server);
. NT的事件記錄器(NT Event Logger);
. UNIX Syslog守護進程(Remote UNIX Syslog daemon);
一個Logger可同時對應多個Appender,示例:myLogger配置二個Appender: 一個file, 一個是console:
log4j.logger.myAppender=WARN,file,console
log4j.appender.file=org.apache.log4j.RollingFileAppender
log4j.appender.file.File=log.txt
log4j.apender.console=org.apache.log4j.ConsoleAppender
4、Layout組件
Layout組件決定日誌輸出格式,有如下幾種類型:
. org.apache.log4j.HTMLLayout(以HTML表格形式佈局);
. org.apache.log4j.PatternLayout(能夠靈活地指定佈局模式);
. org.apache.log4j.SimpleLayout(包含日誌信息的級別和信息字符串);
. org.apache.log4j.TTCCLayout(包含日誌產生的時間、線程和類別等信息);
爲名稱爲console的Appender配置SimpleLayout,代碼以下:
log4j.appender.console.layout=org.apache.log4j.SimpleLayout
輸出日誌格式以下:
WARN - This is a log message from the myLogger
爲名稱爲file的Appender配置PatternLayout,代碼以下:
log4j.appender.file.layout=org.apache.log4j.PatternLayout
log4j.appender.file.layout.ConversionPattern=%t %p - %m%n
輸出日誌格式以下:
THREAD-1 WARN - This is a log message from the myLogger
PatternLayout讓開發者依照ConversionPattern定義輸出格式。ConversionPattern中一些指定日誌內容和格式的預約義符號說明以下:
符號 描述
%r 自程序開始後消耗的毫秒數
%t 表示日誌記錄請求生成的線程
%p 表示日誌語句的優先級
%r 與日誌請求相關的類別名稱
%c 日誌信息所在的類名
%m%n 表示日誌信息的內容
5、Log4J的基本用法
1. 定義配置文件
Log4J支持二種配置文件格式:XML和Java屬性文件(採用「鍵=值」形式)。如下爲Java屬性文件
格式配置文件:
. 配置Logger組件
配置root Logger語法爲:log4j.rootLogger=[priority],appenderName,appenderName,...
配置自定義Logger組件語法爲:log4j.logger.loggerName=[priority],appenderName,appenderName,...
其中:priority爲日誌級別,可選值包括FATAL、ERROR、WARN、INFO、DEBUG、ALL;
appenderName指定Appender組件,可指定多個;
. 配置Appender組件
配置日誌信息輸出目的地Appender, 語法爲:
log4j.appender.appenderName=fully.ualified.name.of.appender.class
log4j.appender.appenderName.option1=value1
...
log4j.appender.appenderName.optionN=valueN
Log4J提供的Appender有如下幾種:
a. org.apache.log4j.ConsoleAppender(控制檯);
b. org.apache.log4j.FileAppender(文件);
c. org.apache.log4j.DailyRollingFileAppender(天天產生一個日誌文件);
d. org.apache.log4j.RollingFileAppender(文件大小到指定尺寸產生一個新的文件);
e. org.apache.log4j.WriteAppender(將日誌信息以流格式發送到任意指定地方);
. 配置Layout組件
配置Layout組件語法爲:
log4j.appender.appenderName.layout=fully.ualified.name.of.appender.class
log4j.appender.appenderName.layout.option1=value1
...
log4j.appender.appenderName.layout.optionN=valueN
下面爲一配置文件示例,文件名爲log4j.properties:
## LOGGERS ##
#configure root logger
log4j.rootLogger=INFO,console
#define a logger named myLogger
log4j.logger.myLogger=WARN
#define a second logger that is a child to myLogger
log4j.logger.myLogger.mySonLogger=,file
## APPENDERS ##
#define an appender named console, which is set to be a ConsoleAppender
log4j.appender.console=org.apache.log4j.ConsoleAppender
# define an appender named file, which is set to be a RollingFileAppender
log4j.appender.file=org.apache.log4j.FileAppender
log4j.appender.file.File=log.txt
## LAYOUTS ##
# assian a SimpleLayout to console appender
log4j.appender.console.layout=org.apache.log4j.SimpleLayout
# assian a PatternLayout to file appender
log4j.appender.file.layout=org.apache.log4j.PatternLayout
log4j.appender.file.layout.ConversionPattern=%t%p-%m%n
2. 程序中使用Log4j
. 得到日誌記錄器:
得到rootLogger:Logger rootLogger=Logger.getRootLogger();
得到自定義Logger:Logger myLogger = Logger.getLogger("log4j.logger.myLogger");
. 讀取日誌記錄器,配置Log4J環境;
a. BasicConfigurator.configure(): 自動快速地使用默認Log4J環境;
b. Property.configurator.configure(String configFilename): 讀取使用Java屬性格式的配置文件並配置Log4J環境;
c. DOMConfigurator.configure(String filename): 讀取XML形式的配置文件並配置LOG4J環境;
. 輸出日誌信息;
在程序代碼中須要生成日誌的地方,調用Logger的各類輸出日誌方法輸出不一樣級別的日誌,例如:
myLogger.debug("Thie is a log message from the " + myLogger.getName());
下面爲一使用Log4J的程序,程序名爲Test.java:
java 代碼
1. import org.apache.log4j.Logger;
2. import org.apache.log4j.PropertyConfigurator;
3.
4. public class Test {
5.
6. public static void main(String[] args) {
7. //Get an instance of the myLogger
8. Logger myLogger = Logger.getLogger("myLogger");
9.
10. //Get an instance of the childLogger
11. Logger mySonLogger = Logger.getLogger("myLogger.mySonLogger");
12. //Load the proerties using the PropertyConfigurator
13. PropertyConfigurator.configure("log4j.properties");
14.
15. //Log Messages using the Parent Logger
16. myLogger.debug("Thie is a log message from the " + myLogger.getName());
17. myLogger.info("Thie is a log message from the " + myLogger.getName());
18. myLogger.warn("Thie is a log message from the " + myLogger.getName());
19. myLogger.error("Thie is a log message from the " + myLogger.getName());
20. myLogger.fatal("Thie is a log message from the " + myLogger.getName());
21.
22. mySonLogger.debug("Thie is a log message from the " + mySonLogger.getName());
23. mySonLogger.info("Thie is a log message from the " + mySonLogger.getName());
24. mySonLogger.warn("Thie is a log message from the " + mySonLogger.getName());
25. mySonLogger.error("Thie is a log message from the " + mySonLogger.getName());
26. mySonLogger.fatal("Thie is a log message from the " + mySonLogger.getName());
27. }
28. }
程序運行結果爲:
WARN - Thie is a log message from the myLogger
ERROR - Thie is a log message from the myLogger
FATAL - Thie is a log message from the myLogger
WARN - Thie is a log message from the myLogger.mySonLogger
ERROR - Thie is a log message from the myLogger.mySonLogger
FATAL - Thie is a log message from the myLogger.mySonLogger
另在Test.class所在的目錄下看到一個log.txt文件,內容以下:
WARN - Thie is a log message from the myLogger.mySonLogger
ERROR - Thie is a log message from the myLogger.mySonLogger
FATAL - Thie is a log message from the myLogger.mySonLogger
如將配置文件log4j.properties中語句
log4j.logger.myLogger.mySonLogger=,file
改成
log4j.logger.myLogger.mySonLogger=,file,console
再次運行程序,結果以下:
WARN - Thie is a log message from the myLogger
ERROR - Thie is a log message from the myLogger
FATAL - Thie is a log message from the myLogger
WARN - Thie is a log message from the myLogger.mySonLogger
WARN - Thie is a log message from the myLogger.mySonLogger
ERROR - Thie is a log message from the myLogger.mySonLogger
ERROR - Thie is a log message from the myLogger.mySonLogger
FATAL - Thie is a log message from the myLogger.mySonLogger
FATAL - Thie is a log message from the myLogger.mySonLogger
mySonLogger的日誌在控制檯上輸出了二次,這是由於mySonLogger繼承了父類console Appender,
自己又定義了一個console Appender, 於是有二個console Appender。
6、在web應用中使用Log4J
建立一個Servlet,在它初始化方法中讀取Log4J配置文件並配置Log4J環境,這個Servlet在Web應用啓
動時候被加載和初始化,而後就可在其它Web組件中獲取Logger對象並輸出日誌。
1. 建立用於配置Log4J環境的Servlet
java 代碼
1. import javax.servlet.*;
2. import javax.servlet.http.*;
3. import java.io.*;
4. import java.util.*;
5.
6. import org.apache.log4j.PropertyConfigurator;
7.
8. public class Log4JServlet extends HttpServlet {
9. public void init() throws ServletException {
10. String path = getServletContext().getRealPath("/");
11. //getInitParameter("propfile")方法從web.xml文件中讀取Log4J配置文件的名字"profile"。
12. String propfile = path + getInitParameter("propfile");
13. PropertyConfigurator.configure(propfile);
14. }
15. }
16.
該Servlet在web.xml中的配置以下:
xml 代碼
1. <servlet>
2. <servlet-name>log4jServlet</servlet-name>
3. <servlet-class>Log4JServlet</servlet-class>
4. <init-param>
5. <param-name>propfile</param-name>
6. <param-value>/WEB-INF/log4j.properties</param-value>
7. </init-param>
8. <load-on-startup>1</load-on-startup>
9. </servlet>
2. 在login.jsp中輸出日誌
<%@page import="org.apache.log4j.Logger"%>
<html>
<head>
<title>login</title>
</head>
<body>
<%
Logger myLogger = Logger.getLogger("myLogger");
Logger mySonLogger = Logger.getLogger("myLogger.mySonLogger");
myLogger.debug("Thie is a log message from the " + myLogger.getName());
myLogger.info("Thie is a log message from the " + myLogger.getName());
myLogger.warn("Thie is a log message from the " + myLogger.getName());
myLogger.error("Thie is a log message from the " + myLogger.getName());
myLogger.fatal("Thie is a log message from the " + myLogger.getName());
mySonLogger.debug("Thie is a log message from the " + mySonLogger.getName());
mySonLogger.info("Thie is a log message from the " + mySonLogger.getName());
mySonLogger.warn("Thie is a log message from the " + mySonLogger.getName());
mySonLogger.error("Thie is a log message from the " + mySonLogger.getName());
mySonLogger.fatal("Thie is a log message from the " + mySonLogger.getName());
%>
<br>
<form name="loginForm" method="post" action="dispatcher">
username: <input type="text" name="username">
<br>
password: <input type="text" name="password">
<br>
<input type="submit" name="submit" value="submit">
</form>
</body>
</html>
3. 發佈運行使用Log4J的web應用
1) 將Log4J的JAR文件拷貝至目錄:<WEB應用所在目錄>/WEB-INF/lib
2) 建立Log4J的配置文件log4j.properties, 存放目錄爲:<WEB應用所在目錄>/WEB-INF。內容同前面配置文件示例。
3) 編譯Log4JServlet, 存放至目錄: <WEB應用所在目錄>/WEB-INF/classes
4) 修改web.xml文件,加入如下內容:
xml 代碼
1. <servlet>
2. <servlet-name>log4jServlet</servlet-name>
3. <servlet-class>Log4JServlet</servlet-class>
4. <init-param>
5. <param-name>profile</param-name>
6. <param-value>/WEB-INF/log4j.properties</param-value>
7. </init-param>
8. <load-on-startup>1</load-on-startup>
9. </servlet>
5) 啓動服務器,訪問login.jsp頁面,在服務器控制檯上看到以下日誌:
WARN - Thie is a log message from the myLogger
ERROR - Thie is a log message from the myLogger
FATAL - Thie is a log message from the myLogger
WARN - Thie is a log message from the myLogger.mySonLogger
ERROR - Thie is a log message from the myLogger.mySonLogger
FATAL - Thie is a log message from the myLogger.mySonLogger
另在<WEB應用所在目錄>/WEB-INF目錄下看到一個log.txt文件,內容以下:
WARN - Thie is a log message from the myLogger.mySonLogger
ERROR - Thie is a log message from the myLogger.mySonLogger
FATAL - Thie is a log message from the myLogger.mySonLogger
7、在log4j.properties配置文件中,結合spring使用web應用根目錄
1.在log4j.properties配置文件中便可將dangdang_bysj.root做爲web應用的根目錄
<context-param>
<param-name>webAppRootKey</param-name>
<param-value>dangdang_bysj.root</param-value>
</context-param>
web.xml配置文件:
<?xml version="1.0" encoding="UTF-8"?>
<web-app xmlns="http://java.sun.com/xml/ns/javaee"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" version="2.5"
xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd">
<display-name>dangdang shopping online system</display-name>
<description>it is a online shopping system</description>
<!--
Key of the system property that should specify the root directory of this
web app. Applied by WebAppRootListener or Log4jConfigListener.
-->
<context-param>
<param-name>webAppRootKey</param-name>
<param-value>dangdang_bysj.root</param-value>
</context-param>
<!--
- Location of the XML file that defines the root application context.
- Applied by ContextLoaderServlet.
-
- Can be set to:
- "/WEB-INF/applicationContext-hibernate.xml" for the Hibernate implementation,
- "/WEB-INF/applicationContext-jpa.xml" for the JPA one, or
- "/WEB-INF/applicationContext-jdbc.xml" for the JDBC one.
-->
<context-param>
<param-name>contextConfigLocation</param-name>
<param-value>
/WEB-INF/classes/context/applicationContext*.xml
</param-value>
</context-param>
<!-- Location of the Log4J config file, for initialization and refresh checks.
Applied by Log4jConfigListener. -->
<context-param>
<param-name>log4jConfigLocation</param-name>
<param-value>/WEB-INF/classes/log4j.properties</param-value>
</context-param>
<!-- Spring ContextLoaderListener Start -->
<listener>
<listener-class>
org.springframework.web.context.ContextLoaderListener
</listener-class>
</listener>
<!-- Spring ContextLoaderListener End -->
<!--
- Configures Log4J for this web app.
- As this context specifies a context-param "log4jConfigLocation", its file path
- is used to load the Log4J configuration, including periodic refresh checks.
-
- Would fall back to default Log4J initialization (non-refreshing) if no special
- context-params are given.
-
- Exports a "web app root key", i.e. a system property that specifies the root
- directory of this web app, for usage in log file paths.
- This web app specifies "petclinic.root" (see log4j.properties file).
-->
<listener>
<listener-class>org.springframework.web.util.Log4jConfigListener</listener-class>
</listener>
<!-- Struts ActionServlet Configuration Start -->
<servlet>
<servlet-name>action</servlet-name>
<servlet-class>org.apache.struts.action.ActionServlet</servlet-class>
<init-param>
<param-name>config</param-name>
<param-value>/WEB-INF/struts-config.xml</param-value>
</init-param>
<init-param>
<description>商品展現模塊</description>
<param-name>config/catalog</param-name>
<param-value>/WEB-INF/catalog-struts-config.xml</param-value>
</init-param>
<init-param>
<description>購物模塊</description>
<param-name>config/shopping</param-name>
<param-value>/WEB-INF/shopping-struts-config.xml</param-value>
</init-param>
<init-param>
<description>用戶管理模塊</description>
<param-name>config/authorize</param-name>
<param-value>/WEB-INF/authorize-struts-config.xml</param-value>
</init-param>
<init-param>
<param-name>debug</param-name>
<param-value>3</param-value>
</init-param>
<init-param>
<param-name>detail</param-name>
<param-value>3</param-value>
</init-param>
<load-on-startup>0</load-on-startup>
</servlet>
<servlet-mapping>
<servlet-name>action</servlet-name>
<url-pattern>*.do</url-pattern>
</servlet-mapping>
<!-- Struts ActionServlet Configuration Start -->
<welcome-file-list>
<welcome-file>index.jsp</welcome-file>
<welcome-file>index.html</welcome-file>
<welcome-file>index.htm</welcome-file>
<welcome-file>default.jsp</welcome-file>
<welcome-file>default.html</welcome-file>
<welcome-file>default.htm</welcome-file>
</welcome-file-list>
<session-config>
<session-timeout>30</session-timeout>
</session-config>
</web-app>
2.log4j.properties配置文件 使用${dangdang_bysj.root}來指明web應用根目錄
# For JBoss: Avoid to setup Log4J outside $JBOSS_HOME/server/default/deploy/log4j.xml!
# For all other servers: Comment out the Log4J listener in web.xml to activate Log4J.
log4j.rootLogger=INFO, stdout, logfile
log4j.appender.stdout=org.apache.log4j.ConsoleAppender
log4j.appender.stdout.layout=org.apache.log4j.PatternLayout
log4j.appender.stdout.layout.ConversionPattern=%d %p [%c] - %m%n
log4j.appender.logfile=org.apache.log4j.RollingFileAppender
log4j.appender.logfile.File=${dangdang_bysj.root}/WEB-INF/log/dangdang_bysj.log
log4j.appender.logfile.MaxFileSize=512KB
# Keep three backup files.
log4j.appender.logfile.MaxBackupIndex=3
# Pattern to output: date priority [category] - message
log4j.appender.logfile.layout=org.apache.log4j.PatternLayout
log4j.appender.logfile.layout.ConversionPattern=%d %p [%c] - %m%n
log4j.appender.org.apache.commons.digester.Digester.sax=DEBUG
#Jdbc logging configuration...
log4j.logger.java.sql.Connection=DEBUG
log4j.logger.java.sql.Statement=DEBUG
log4j.logger.java.sql.PreparedStatement=DEBUG
log4j.logger.java.sql.ResultSet=DEBUG
#Dang_bysj logging configuration...
log4j.appender.org.nit.dang=DEBUG
#Spring logging configuration... log4j.logger.org.springframework.jdbc.datasource.DataSourceTransactionManager=DEBUG