1: Introduction to Log4j Introduction
Log4j is an open source project of Apache. By using Log4j, we can control the destinations of log information delivery to consoles, files, GUI components, and even socket servers, NT event loggers, UNIX Syslog daemons, etc.; We can also control the output format of each log; by defining the level of each log information, we can control the log generation process more carefully. What is most interesting is that these can be configured flexibly through a configuration file without modifying the application's code.
In addition, through Log4j other language interfaces, you can use Log4j in C, C++, .Net, PL/SQL programs. Its syntax and usage are the same as in Java programs, so that multilingual distributed systems can obtain a unified and consistent log component. Module. Moreover, by using various third-party extensions, you can easily integrate Log4j into J2EE, JINI, and even SNMP applications.
2. Beginner examples
1. Create a new JAva project, import the package log4j-1.2.17.jar, and the final directory of the entire project is as follows
2. Create and set log4j.properties at the same level
### set up###
log4j.rootLogger = debug,stdout,D,E
### Output information to control lift####
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 = [%-5p] %d{yyyy-MM-dd HH:mm:ss,SSS} method:%l%n%m%n
### Output logs above DEBUG level to =E://logs/error.log ###
log4j.appender.D = org.apache.log4j.DailyRollingFileAppender
log4j.appender.D.File = E://logs/log.log
log4j.appender.D.Append = true
log4j.appender.D.Threshold = DEBUG
log4j.appender.D.layout = org.apache.log4j.PatternLayout
log4j.appender.D.layout.ConversionPattern = %-d{yyyy-MM-dd HH:mm:ss} [ %t:%r ] - [ %p ] %m%n
### Output logs above the ERROR level to =E://logs/error.log ###
log4j.appender.E = org.apache.log4j.DailyRollingFileAppender
log4j.appender.E.File =E://logs/error.log
log4j.appender.E.Append = true
log4j.appender.E.Threshold = ERROR
log4j.appender.E.layout = org.apache.log4j.PatternLayout
log4j.appender.E.layout.ConversionPattern = %-d{yyyy-MM-dd HH:mm:ss} [ %t:%r ] - [ %p ] %m%n
3. Set log content
package com.mucfc;import org.apache.log4j.Logger;/** *@author linbingwen *@May 18, 2015 9:14:21 */public class Test { private static Logger logg er = Logger.getLogger(Test .class); /** * @param args */ public static void main(String[] args) { // System.out.println("This is println message."); // Record debug level information logger. : : : : : : : : : : : : : : : : : : : : : : : : : : : : : : : : : : : : : : : : : : : : : : : : : : : : : : : : : : : : : : : : : : : : : : : : : : : : : : : : : : : : : : : : : : : : : : : : : : : : : : : : : : : : : : : : : : : : : : : : : : : : : : : debug("This is debug message."); // Record info-level information logger.info("This is info message."); // Record error-level information logger.error("This is error message.") ; } }4. Output result
(1) First of all, the information of the console
(2) Let's look at the output file
The content is as follows, and it is found that it has been output to the corresponding document as required.
3. Basic usage method of Log4j
Log4j consists of three important components: the priority of log information, the output destination of log information, and the output format of log information. The priority of log information is from high to low. ERROR, WARN, INFO, and DEBUG, which are used to specify the importance of this log information; the output destination of the log information specifies whether the log will be printed to the console or file; and the output is The format controls the display content of the log information.
2.1. Define configuration files
In fact, you can also not use configuration files at all, but configure the Log4j environment in your code. However, using configuration files will make your application more flexible. Log4j supports two configuration file formats, one is an XML format file, and the other is a Java feature file (key = value). Below we introduce the method of using Java feature files as configuration files:
1. Configure the root logger, its syntax is:
log4j.rootLogger = [ level ] , appenderName, appenderName, …
Among them, level is the priority of logging, divided into OFF, FATAL, ERROR, WARN, INFO, DEBUG, ALL or the level you define. Log4j recommends using only four levels, with priority from high to low, namely ERROR, WARN, INFO, and DEBUG. By the level defined here, you can control the switches to the corresponding level of log information in the application. For example, if the INFO level is defined here, all DEBUG level log information in the application will not be printed out. appenderName refers to where the B log information is output to. You can specify multiple output destinations at the same time.
2. Configure the destination Appender to output the log information, and its syntax is:
log4j.appender.appenderName = fully.qualified.name.of.appender.class
log4j.appender.appenderName.option1 = value1
…
log4j.appender.appenderName.option = valueN
Among them, the appenders provided by Log4j are as follows:
org.apache.log4j.ConsoleAppender (Console),
org.apache.log4j.FileAppender (file),
org.apache.log4j.DailyRollingFileAppender (generates one log file every day),
org.apache.log4j.RollingFileAppender (a new file is generated when the file size reaches the specified size),
org.apache.log4j.WriterAppender (send log information in stream format to any specified place)
3. Configure the format (layout) of log information, and its syntax is:
log4j.appender.appenderName.layout = fully.qualified.name.of.layout.class
log4j.appender.appenderName.layout.option1 = value1
…
log4j.appender.appenderName.layout.option = valueN
Among them, there are several layouts provided by Log4j:
org.apache.log4j.HTMLLayout (layout in HTML table form),
org.apache.log4j.PatternLayout (the layout mode can be flexibly specified),
org.apache.log4j.SimpleLayout (contains the level and information string of log information),
org.apache.log4j.TTCCLayout (including time, thread, category, etc. of log generation)
Log4J uses a print format similar to the printf function in C language to format the log information, and the printing parameters are as follows: %m The message specified in the output code
%p output priority, i.e. DEBUG, INFO, WARN, ERROR, FATAL
%r Output the number of milliseconds taken from the start of the application to output the log information
%c outputs the category, usually the full name of the class it is located
%t outputs the thread name that generates the log event
%n outputs a carriage return line break, Windows platform is "rn", Unix platform is "n"
%d outputs the date or time of the log time point. The default format is ISO8601. You can also specify the format afterwards, such as: %d{yyy MMM dd HH:mm:ss,SSS}, and the output is similar: October 18, 2002 22:10:28, 921
%l Output the location where the log event occurs, including the class name, the thread that occurred, and the number of lines in the code. Example: Testlog4.main(TestLog4.java:10)
2.2. Use Log4j in the code
1. Get the recorder
Using Log4j, the first step is to obtain the log recorder, which will be responsible for controlling the log information. The syntax is:
public static Logger getLogger( String name)
Get the logger by the specified name and, if necessary, create a new logger for the name. Name is generally named in this class, such as:
static Logger logger = Logger.getLogger ( ServerWithLog4j.class.getName () )
2. Read the configuration file
After obtaining the logger, the second step will configure the Log4j environment, with the syntax as:
BasicConfigurator.configure (): Automatically and quickly use the default Log4j environment.
PropertyConfigurator.configure ( String configFilename ): Read configuration files written using Java's feature files.
DOMConfigurator.configure ( String filename ): Read configuration files in XML form.
3. Insert record information (format log information)
When the previous two necessary steps are completed, you can easily insert the logging statements of different priority levels anywhere you want to log. The syntax is as follows:
Logger.debug ( Object message ) ;
Logger.info ( Object message ) ;
Logger.warn ( Object message ) ;
Logger.error ( Object message ) ;
2.3. Log level
Each Logger is subjected to a log level (log level) to control the output of log information. Log levels are divided into:
A: off The highest level is used to close all logging.
B: fatal indicates that each critical error event will cause the application to exit.
C: error indicates that although an error event occurs, it still does not affect the continued operation of the system.
D: warm indicates that there will be potential error situations.
E: info Generally and at the coarse-grained level, it emphasizes the entire operation of the application.
F: debug is generally used at the fine-grained level and is very helpful for debugging applications.
G: all minimum level, used to open all logging.
The above levels are defined in the org.apache.log4j.Level class. Log4j only recommends using 4 levels, with priority from high to low, error, warn, info and debug. By using the log level, you can control the output of log information at the corresponding level in the application. For example, if b is used, all log information below the info level (such as debug) in the application will not be printed out.
4. Use Log4j instances in web projects
The above code describes the simple application of Log4j, and in fact, using Log4j is so simple and convenient. Of course, in addition to the above configuration method, there are other things, such as making a J2EE application. When using Log4j in J2EE application, you must first load the Log4j configuration file when starting the service and initialize it, which can be performed in web.xml.
1. The log4j usage of web applications basically uses: create a new servlet, which executes configuration for log4j in the init function. Generally, it is to read the configuration file. Therefore, you need to configure this servlet in web.xml, and set load-on-startup to 1.
2. This servlet configuration log4j is to read out the configuration file and then call the configure function. There are two questions here: 1. You need to know where the file is; 2. You need the correct file type
3. Configuration file location can be configured in web.xml. The path is generally relative to the root directory of the web.
4. There are generally two types of file types, one is Java property file, and the other is XML file
The general content of the configuration file: log4j can specify the minimum level of the output log level, as well as the output configuration format of the log. Each log can specify multiple output methods.
(1) Create a web project, the final directory of the entire project is as follows
(2) The web.xml configuration is as follows:
<?xml version="1.0" encoding="UTF-8"?> <web-app xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns="http://java .sun.com/xml/ns/javaee" xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_3_0 .xsd" id="WebApp_ID" version="3.0"> <display-name>LogLearning</display-name> <servlet> <servlet-name>Log4JTestServlet</servlet-name> <servlet-cl ass>com.mucfc. Log4JTestServlet</servlet-class> </servlet> <!-- servlet used to start log4jConfigLocation --> <servlet> <servlet-name>Log4JInitServlet</servlet-name> <servlet-cla ss>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> <servlet-mapping> <servlet-name>Log4JTestServlet</servlet-name> <url-pattern>/test</url -pattern> </servlet-mapping> </web-app>
(3) Configuration file log4j.properties
### set log levels ###
log4j.rootLogger = debug,stdout,D,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 = [%-5p] %d{yyyy-MM-dd HH:mm:ss,SSS} method:%l%n%m%n
log4j.appender.D = org.apache.log4j.DailyRollingFileAppender
log4j.appender.D.File = F://logs/log.log
log4j.appender.D.Append = true
log4j.appender.D.Threshold = DEBUG
log4j.appender.D.layout = org.apache.log4j.PatternLayout
log4j.appender.D.layout.ConversionPattern = %-d{yyyy-MM-dd HH:mm:ss} [ %t:%r ] - [ %p ] %m%n
log4j.appender.E = org.apache.log4j.DailyRollingFileAppender
log4j.appender.E.File =F://logs/error.log
log4j.appender.E.Append = true
log4j.appender.E.Threshold = ERROR
log4j.appender.E.layout = org.apache.log4j.PatternLayout
log4j.appender.E.layout.ConversionPattern = %-d{yyyy-MM-dd HH:mm:ss} [ %t:%r ] - [ %p ] %m%n
(4) The servlet initialized as soon as the web container comes
Log4JInitServlet.javapackage com.mucfc; import java.io.File; import java.io.IOException; import javax.servlet.ServletConfig; import javax.servlet. ServletContext; import javax.servlet.ServletException; import javax.servlet.annotation.WebServlet ; import javax.servlet.http.HttpServlet; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import org.apa che.log4j.BasicConfigurator; import org.apache.log4j.PropertyConfigurator; /** * Servlet implementation class Log4JInitServlet */ @WebServlet("/Log4JInitServlet") public class Log4JInitServlet extends HttpServlet { private static final long s eraalVersionUID = 1L; /** * @see HttpServlet#HttpServlet() */ public Log4JInitServlet() { super(); // TODO Auto-generated constructor stub } /** * @see Servlet#init(ServletConfig) */ public void init(ServletConfig config) throws ServletException { Systeme m.out.println("Log4JInitServlet is initializing log4j log setting information"); String log4jLocation = config.getInitParameter("log4j-properties-location"); ServletContext sc = config.getServletContext(); if (log4jLocation == nul l) { System.err.println("*** No log4j-properties-location initialization file, so use BasicConfigurator to initialize"); BasicConfigurator.configure(); } else { String webAppPath = sc.getRealPath("/"); String log4jProp = webAppPath + l og4jLocation; File yoMamaYesThisSaysYoMama = new File(log4jProp); if (yoMamaYesThisSaysYoMama .exists()) { System.out.println("Use: " + log4jProp + "Initialize log setting information"); PropertyConfigurator.configure(log4jProp); } else { System.err.println("*** " + log4jProp + "The file was not found, so initialized with BasicConfigurator"); BasicConfigurator.configure(); } } super.init(config); } /** * @see HttpServlet#doGet(HttpServletRequest request est, HttpServletResponse response) */ protected void doGet( HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { // TODO Auto-generated method stub } /** * @see HttpServle t#doPost(HttpServletRequest request, HttpServletResponse response) */ protected void doPost(HttpServletRequest request, HttpServletResponse response) throw s ServletException , IOException { // TODO Auto-generated method stub } }Call log Log4JTestServlet,java
package com.mucfc; import java.io.IOException; import javax.servlet.ServletConfig; import javax.servlet.ServletException; import javax.servlet.annot ation.WebServlet; import javax.servlet.http.HttpServlet; import javax.servlet.http .HttpServletRequest; import javax.servlet.http.HttpServletResponse; import org.apache.log4j.Logger; /** * Servlet implementation class Log4JTestServlet */ @WebServlet("/Log4JTestServlet") public class Log4JTestServlet extends HttpServlet { private static final long serialVersionUID = 1L; private static Logger logger = Logger.getLogger(Log4JTestServlet.class); /** * @see HttpServlet#HttpServlet() */ public Log4JTestServlet() { super(); // TODO Auto-generated constructor stub } /* * * @see Servlet#init(ServletConfig) */ public void init(ServletConfig config) throws ServletException { // TODO Auto-generated method stub } /** * @ see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse response) */ protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { // Record debug level information logger.debug("This is debug m essage."); // Record info-level information logger.info("This is info message ."); // Record error level information logger.error("This is error message."); } /** * @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse response) */ protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { doGet(request,response); } }Next is running, let’s see the results:
Output result:
5. Use Log4j in Spring
Here we need to implement the use of Spring in web projects to use Log4j
(1) Connect to the above project and then import the Spring package
(2) web.xml added
<!-- Set root directory --> <context-param> <param-name>webAppRootKey</param-name> <param-value>webapp.root</param-value> </context-param> <context- param> <param-name>log4jConfigLocation</param-name> <param-value>/WEB-INF/classes/log4j.properties</param-value> </context-param> <!-- 3000 means one opening watchdog The thread scans the configuration file changes every 60 seconds; this facilitates the change of log storage location--> <context-param> <param-name>log4jRefreshInterval</param-name> <param-value>3000</param-value> </context-param> <listener> <listener-class>org.springframework.web.util.Log4jConfigListener</listener-class> </listener>
The whole content is as follows:
<?xml version="1.0" encoding="UTF-8"?> <web-app xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns="http://java .sun.com/xml/ns/javaee" xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_3_0 .xsd" id="WebApp_ID" version="3.0"> <display-name>LogLearning</display-name> <servlet> <servlet-name>Log4JTestServlet</servlet-name> <servlet-cl ass>com.mucfc. Log4JTestServlet</servlet-class> </servlet> <!-- servlet used to start log4jConfigLocation --> <!-- <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.p roperties</param-value > </init-param> <load-on-startup>1</load-on-startup> </servlet>--> <servlet-mapping> <servlet-name>Log4JTestServlet</servlet-name> <url- pattern>/test</url-pattern> </servlet-mapping> <!-- Spring container loading--> <listener> <listener-class>org.springframework.web.context.ContextLoaderListener</list ener-class> < /listener> <context-param> <param-name>contextConfigLocation</param-name> <param-value>classpath:applicationContext.xml</param-value> </context-par am> <!-- Set root directory- -> <context-param> <param-name>webAppRootKey</param-name> <param-value>webapp.root</param-value> </context-param> <context-param> <param-name >log4jConfigLocation </param-name> <param-value>/WEB-INF/classes/log4j.properties</param-value> </context-param> <!-- 3000 means opening a watchdog thread to scan the configuration file every 60 seconds Changes; this facilitates the change of log storage location--> <context-param> <param-name>log4jRefreshInterval</param-name> <param-value>3000</param-value> </context-param> <listener > <listener-class>org.springframework.web.util.Log4jConfigListener</listener-class> </listener> </web-app>
Here Log4JInitServlet.java is equivalent to being useless.
(2) applicationContext.xml
No content:
<?xml version="1.0" encoding="UTF-8"?> <beans xmlns="http://www.springframework.org/schema/beans" xmlns:xsi="http://www.w3.org /2001/XMLSchema-instance" xmlns:context="http://www.springframework.org/schema/context" xmlns:aop="http://www.springframework.org/sche ma/aop" xsi:schemaLocation=" http://www.springframework.org/schema/beanshttp://www.springframework.org/schema/beans/spring-beans-3.2.xsdhttp://www.springframework.org /schema/aophttp://www. springframework.org/schema/aop/spring-aop-3.2.xsdhttp://www.springframework.org/schema/context http://www.springframework.org/schema/cont ext/spring-context-3.2.xsd"> </beans>
(3) In this way, the log will be started with the Spring window
Once the program is run, the log will be printed automatically
log.log
error.log is empty because it only prints information above the error level
Enter http://localhost:8080/LogLearning2/test by the browser
Then open the file
The detailed tutorial on Java log4j is over here. The following article will introduce to you the java web log4j configuration and the skills of configuring Log4j in web projects. Interested friends will continue to follow this site.