log4j快速上手
Log4J是Apache的一个开放源代码项目(http://logging.apache.org/log4j/docs/),它是一个日志操作包。通过使用Log4J,可以指定日志信息输出的目的地,控制每一条日志的输出格式,定义日志信息的级别。所有这些功能通过一个配置文件灵活进行配置。
一、LOG4J组成
LOG4J主要由三大组件组成:
. Logger: 决定什么日志信息应该被输出、什么日志信息应该被忽略;
. Appender: 指定日志信息应该输出到什么地方, 这些地方可以是控制台、文件、网络设备;
. Layout: 指定日志信息的输出格式;
一个Logger可以有多个Appender,也就是说日志信息可以同时输出到多个设备上,每个Appender对应
一种Layout(示例见下图)。
↗ Appender1 → Layout
/
Logger
﹨
↘ Appender2 → Layout
二、Logger组件
1. Logger组件提供的方法:
Logger组件是LOG4J的核心组件,它代表了Log4J的日志记录器,它能够对日志信息进行分类筛选。它由org.apache.log4j.Logger类实现,提供了如下方法:
java 代码
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. }
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(继承)
三、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
四、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 表示日志信息的内容
五、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。
六、在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
七、在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
上一篇: python笔记 元组
下一篇: java io乱码怎么办