Log4J is an open source Apache Project ( http://logging.apache.org/log4j/docs/ ), which is a packet logging operation. By using the Log4J, to specify the destination of the log information output, controls the output format of each log, the log level definition information. All of these features are configurable through a configuration file flexible.
A, LOG4J composition
LOG4J mainly consists of three components:
Logger: log decide what information should be output, log what information should be ignored;.
Appender:. Specify the log information to be output to any place, these places can be a console, file, network equipment;
. Layout: specify the output format of the log information;
Can have a plurality of Appender Logger, that is log information may be output to multiple devices simultaneously, each corresponding to Appender
one kind Layout (examples see below).
↗ Appender1 → Layout
/
Logger
﹨
↘ Appender2 → Layout
Two, Logger component
1. A method Logger component provides:
Logger component is the core component of LOG4J, which represents the Log4J logger, which can be classified screened for log information. It is implemented by org.apache.log4j.Logger class provides the following methods:
java code
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. Configure Logger component in the configuration file
Logger own configurable components, examples Log4J configuration file:
log4j.logger.myLogger=WARN
Logger above code defines a component name myLogger, log level is WARN.
3. Log Level Category:
There are five, level descending order: fatal, error, warn, info, debug. After obtaining Logger instance, we can call one of the following methods to output log information:
public void debug (Object message); // output level debug log information;
public void info (Message Object); // info level output log information;
public void warn (Message Object); // log information output levels warn ;
public void error (message Object); // output level of error log information;
public void fatal (message Object); // fatal level log output information;
public void log (P the Priority, message Object); // output parameters Priority Specifies the level of log information;
The above method is called only when the log level greater than or equal to its level Logger assembly configuration. To myLogger front of our configuration example, its log level is WARN, then in the program, it warn (), error (), fatal () method will be executed. For the log () method, it is only when the specified parameter Priority level is greater than or equal to log WARN, it will be executed.
4. Why do you need to log grading?
When writing the program, in order to debug the program, we will output a lot of log information in many places error. When the program finished debugging, this information is not required, the program will output log information in these codes delete it? So time-consuming, almost infeasible for large programs. By classifying the log, the log information if do not want to WARN output level is raised to the level of Logger components, save time and worry.
5. Logger assembly inheritance
Log4J provides a root Logger, it is all Logger component "ancestor", it will always exist, and can not be retrieved by name or reference, made it through Logger.getRootLogger () method. Configuring root Logger Code:
log4j.rootLogger = INFO, console
May conveniently be arranged in the configuration file exists Logger assembly inheritance relationship, all the symbols. "" The assembly will later become the symbol. "" Subclass Logger foregoing components. E.g:
log4j.apache.myLogger=WARN
log4j.apache.myLogger.mySonLogger=,file
The above code, mySonLogger is myLogger subclass Logger assembly. Inheritance Logger component:
If the component does not define a subclass Logger log level will log level of the parent class inheritance;
if subclass Logger component defines the log level, the log level will not inherit the parent class;.
Default. under subclass Logger component will inherit the parent of all the Appender, add them to their Appener;
. If additivity flag handle class Logger component set to false, then it will not inherit the parent class Appender. The default value additivity flag false;
Logger three examples shown in the above configuration inheritance:
root Logger: log level = INFO appender Console list =
↑
myLogger: log level = WARN appender null list =
↑
mySonLogger: log level = null appender list = file
These three components Logger level and the actual log Appender the following table:
Logger component log level Appender list of
root Logger INFO Console
myLogger WARN Console (inherited)
mySonLogger WARN (inherited) file, console (inherited)
three, Appender components
Appender assembly decided to log information output to any place. Supports the following destinations:
. Console (Console);
. File (File);
. The GUI components (the GUI the Component);
. Socket server (Remote Server socket);
. NT event recorder (NT Event Logger);
. UNIX Syslog daemon (Remote UNIX Syslog daemon);
Logger correspond to a plurality of simultaneously Appender, Example: myLogger arranged two Appender: a file, is a 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
Four, Layout Components
Layout component determines log output format, the following types:
. Org.apache.log4j.HTMLLayout (HTML table format layout);
. Org.apache.log4j.PatternLayout (flexibility to specify the layout mode);
. The org.apache .log4j.SimpleLayout (including log information and level information and character string);
. Org.apache.log4j.TTCCLayout (log contains time generated, thread, and category information);
configured to SimpleLayout Appender console to the name, as follows:
log4j.appender.console.layout=org.apache.log4j.SimpleLayout
Output log format is as follows:
WARN - This is a log message from the myLogger
name of the configuration file to PatternLayout Appender, code is as follows:
log4j.appender.file.layout=org.apache.log4j.PatternLayout
log4j.appender.file.layout.ConversionPattern=%t %p - %m%n
Output log format is as follows:
THREAD-1 WARN - This is a log message from the myLogger
PatternLayout ConversionPattern allows developers to define the output in accordance with the format. ConversionPattern some predefined symbols specify the content and format of the log follows:
Symbol Description
Number of milliseconds after the beginning of consumption% r from procedures
% t represents the log recording request to generate a thread
priority% p represents the log statement
% r and log requests related to the category name
% c class name log information resides
% m% n It represents the contents of the log information
Fifth, the basic usage of Log4J
1. Define profile
Log4J configuration file format supports two kinds: XML and Java properties (a "key = value" format). The following is a Java properties file
format configuration file:
Configuring Logger component
configured root Logger syntax is: log4j.rootLogger = [priority], appenderName , appenderName, ...
configure a custom Logger component syntax is: log4j.logger.loggerName = [priority ], appenderName, appenderName, ...
Wherein: priority level as a log, including optional values FATAL, ERROR, WARN, the INFO, the DEBUG, ALL;
AppenderName Appender specified component, can specify a plurality;
Configuring Components Appender
Configuration information log output destination Appender, the syntax is:
log4j.appender.appenderName = fully.ualified.name.of.appender.class
log4j.appender.appenderName.option1 = value1
...
log4j.appender.appenderName.optionN = valueN
Appender Log4J provided are the following:
. a org.apache.log4j.ConsoleAppender (console);
. org.apache.log4j.FileAppender B (documents);
. org.apache.log4j.DailyRollingFileAppender C (generating a log file per day);
. D the org.apache. log4j.RollingFileAppender (file size to a specified size to generate a new file);
. E org.apache.log4j.WriteAppender (log stream format information is sent to any given place);
configuration Layout component
配置Layout组件语法为:
log4j.appender.appenderName.layout=fully.ualified.name.of.appender.class
log4j.appender.appenderName.layout.option1=value1
...
log4j.appender.appenderName.layout.optionN=valueN
The following is an example of the configuration file, the file name 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
Obtained logger:
Obtained rootLogger: Logger rootLogger = Logger.getRootLogger () ;
obtaining custom Logger: Logger myLogger = Logger.getLogger ( " log4j.logger.myLogger");
The reader logger configuration Log4J environment;
. a BasicConfigurator.configure (): Automatic use Log4J default environment;
B Property.configurator.configure (String configFilename):. attribute format is read using Java profile and configure Log4J environment;
C DOMConfigurator.configure (String filename. ): read XML configuration files and configure the form LOG4J environment;
The output of the log information;
In the program code needed to generate the local log Logger call log output method of outputting a variety of different levels of logging, such as:
myLogger.debug ( "Thie IS A log Message from The" + myLogger.getName ());
The following is a use Log4J program, program name Test.java:
Java Code
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. }
As a result of the program:
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
Another saw a log.txt file in the directory where Test.class, reads as follows:
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
As in the configuration file log4j.properties statement
log4j.logger.myLogger.mySonLogger=,file
Changed
log4j.logger.myLogger.mySonLogger=,file,console
Run the program again, results are as follows:
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 log on the console output of the secondary, because mySonLogger inherits the parent class console Appender,
in turn, we define a console Appender, so there are two console Appender.
Sixth, in web applications using Log4J
Creating a Servlet, it reads initialization method Log4J configuration files and configure Log4J environment, this Servlet in Web applications start
moving when they were loaded and initialized, then you can get a Logger object in the other Web components and output log.
1. Create an environment for configuring Log4J Servlet
the Java Code
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.
The Servlet web.xml configuration is as follows:
XML Code
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>
<the INPUT of the type = "the Submit" name = "the Submit" value = "the Submit">
</ form>
</ body>
</ HTML>
3. Published run web applications using Log4J
1) copy Log4J JAR file to the directory: <WEB application directory> / the WEB-INF / lib
2) create Log4J configuration file log4j.properties, storage directory: <WEB application directory> / WEB-INF. Content with the previous example configuration file.
3) compilation Log4JServlet, stored to the directory: <WEB application directory> / the WEB-INF / classes
. 4) modify the web.xml file, add the following:
XML Code
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) Start the server, access login.jsp page, see the following at the server console log:
WARN - Thie IS A log from the Message at The myLogger
ERROR - Thie IS A log from the Message at The myLogger
FATAL - Thie IS A log from the Message at The myLogger
WARN - log Thie IS A Message from The myLogger.mySonLogger
ERROR - log Thie IS A Message from The myLogger.mySonLogger
FATAL - log Thie IS A Message from The myLogger.mySonLogger
Another saw a log.txt file in the <WEB application directory> / WEB-INF directory, as follows:
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
Seven, in the log4j.properties configuration file, with spring using a web application root directory
1. In the log4j.properties configuration file to the root directory of the dangdang_bysj.root as a web application
<context-param>
<param-name>webAppRootKey</param-name>
<param-value>dangdang_bysj.root</param-value>
</context-param>
web.xml configuration file:
<?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 profile $ {dangdang_bysj.root} used to indicate the web application root
# 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
Reproduced in: https: //my.oschina.net/u/1167421/blog/546490