Logs are an integral part of the application software, and Apache's Open source projectlog4jis a powerful log component that provides convenient logging. On the Apache website: jakarta.apache.org/log4j can be downloaded free of charge to the latest version of the LOG4J package.
I. Examples of getting Started
1. Create a new Java project, import the package Log4j-1.2.17.jar, the entire project final directory is as follows
2. SRC peers Create and set log4j.properties
# # # #log4j. Rootlogger = debug,stdout,d,e### output information to control lift # # #log4j. appender.stdout = Org.apache.log4j.ConsoleAppenderlog4j.appender.stdout.Target = System.outlog4j.appender.stdout.layout = Org.apache.log4j.PatternLayoutlog4j.appender.stdout.layout.ConversionPattern = [%-5p]%d{yyyy-mm-dd Hh:mm:ss,sss} method:%l%n%m%n### output debug levels above the log to =e://logs/error.log # # #log4j. APPENDER.D = Org.apache.log4j.dailyrollingfileappenderlog4j.appender.d.file = E://logs/log.loglog4j.appender.d.append = Truelog4j.appender.d.threshold = DEBUG Log4j.appender.d.layout = Org.apache.log4j.patternlayoutlog4j.appender.d.layout.conversionpattern =%-d{yyyy-mm-dd HH:mm:ss} [%t:%r]-[%p]%m %n### output error level above the log to =e://logs/error.log # # #log4j. APPENDER.E = Org.apache.log4j.dailyrollingfileappenderlog4j.appender.e.file =e://logs/error.log log4j.appender.E.Append = Truelog4j.appender.e.threshold = ERROR Log4j.appender.e.layout = Org.apache.log4j.patternlayoutlog4j.appender.e.layout.conversionpattern =%-d{yyyy-mm-dd HH:MM:SS} [%t:%r]-[%p]%m%n
3. Set the log contents
Package Com.mucfc;import org.apache.log4j.logger;/** * @author Linbingwen *@2015 May 18 9:14:21 */public class Test { private static Logger Logger = Logger.getlogger (test.class); /** * @param args * /public static void main (string[] args) { //System.out.println ("This is println mess Age. "); Record the debug level information logger.debug ("This is debug message."); Log information for info level Logger.info ("This is info message."); Record the error level information logger.error ("This is the error message.");}
4. Output results
(1) First, the information of the console
(2) Look at the output file again
The content is as follows, and the discovery has been output to the corresponding document as required.
Second, log4j basic use method
LOG4J consists of three important components: the priority of the log information, the output destination of the log information, and the output format of the log information. The priority of log information is high to low with error, WARN, INFO, DEBUG, respectively, 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 the file, and the output format controls the display of the log information.
2.1. Define the configuration file
In fact, you can also configure the LOG4J environment in your code without using the configuration file at all. However, using a configuration file will make your application more flexible. LOG4J supports two configuration file formats, one in XML format and one Java attribute file (key = value). Here's how to use the Java attributes file as a configuration file:
1. Configure the root logger, whose syntax is:
Log4j.rootlogger = [level], Appendername, Appendername, ...
Level is the priority of logging, which is divided into off, FATAL, ERROR, WARN, INFO, DEBUG, all, or levels you define. LOG4J recommends using only four levels, with the priority from high to low being error, WARN, INFO, DEBUG. By defining the level here, you can control the switch to the appropriate level of log information in your application. For example, if the info level is defined here, the log information for all debug levels in the application will not be printed. Appendername refers to where the B log information is exported. You can specify multiple output destinations at the same time.
2. Configure the log information output destination Appender, whose syntax is:
Log4j.appender.appenderName = Fully.qualified.name.of.appender.class Log4j.appender.appenderName.option1 = Value1 ... Log4j.appender.appenderName.option = Valuen
Among them, LOG4J provides the following types of Appender:
Org.apache.log4j.ConsoleAppender (console), org.apache.log4j.FileAppender (file), Org.apache.log4j.DailyRollingFileAppender (generates a log file every day), Org.apache.log4j.RollingFileAppender (creates a new file when the file size reaches the specified size), Org.apache.log4j.WriterAppender (send log information in stream format to any specified location)
3. Configure the format (layout) of the log information with the following syntax:
Log4j.appender.appenderName.layout = Fully.qualified.name.of.layout.class Log4j.appender.appenderName.layout.option1 = value1 ... Log4j.appender.appenderName.layout.option = Valuen
Among them, the layout provided by log4j has several types of E:
Org.apache.log4j.HTMLLayout (layout in an HTML table), org.apache.log4j.PatternLayout (with the flexibility to specify layout mode), Org.apache.log4j.SimpleLayout (contains the level and information string for log information), org.apache.log4j.TTCCLayout (contains information such as the time, thread, category, etc.) of the log generation
log4j formats the log information in a print format similar to the printf function in C, with the following printing parameters:%m The message specified in the output code
%p output priority, which is the debug,info,warn,error,fatal %r output from the application boot to output the log information in milliseconds the output belongs to the class, usually the full name of the class %t output the name of the thread that generated the log event %n output A carriage return newline character, the Windows platform is "RN", the UNIX platform is "n" %d output log time point of the date or time, the default format is ISO8601, can also be specified after the format, such as:%d{yyy MMM DD HH:mm:ss, SSS}, output similar to: October 18, 2002 22:10:28,921%l The occurrence of the output log event, including the class name, the thread that occurred, and the number of rows in the code. Example: Testlog4.main (testlog4.java:10)
2.2. Use log4j in code
1. Get the Recorder
Using log4j, the first step is to get the logger, which will be responsible for controlling the log information. Its syntax is:
public static Logger GetLogger (String name)
The logger is obtained by the specified name and, if necessary, a new logger is created for the name. Name generally takes the names of this class, such as:
static Logger Logger = Logger.getlogger (ServerWithLog4j.class.getName ())
2. Read the configuration file
When the logger is obtained, the second step configures the LOG4J environment with the following syntax:
Basicconfigurator.configure (): Automatically and quickly using the default log4j environment. propertyconfigurator.configure (String configfilename): Reads a configuration file written using the Java properties file. domconfigurator.configure (String filename): Reads the configuration file in XML form.
3. Inserting record information (formatting log information)
When the two necessary steps are completed, you can easily insert a logging statement with different priority levels into any place you want to log, with the following syntax:
Logger.debug (Object message); Logger.info (Object message); Logger.warn (Object message); Logger.error (Object message);
2.3. Log level
Each logger is logged at a log level to control the output of the log information. The log level is divided from high to Low:
A:off the highest level for closing all log records.
B:fatal indicates that each serious error event will cause the application to exit.
C:error points out that although an error event occurs, it still does not affect the system's continued operation.
D:warm indicates that a potential error condition occurs.
E:info general and at the coarse-grained level, the application is emphasized throughout the run.
F:debug is generally used for fine-grained levels and is very helpful for debugging applications.
G:all the lowest level to open all log records.
The above levels are defined in the Org.apache.log4j.Level class. Log4j only recommends using 4 levels, with priority levels from high to low for Error,warn,info and debug respectively. By using the log level, you can control the output of the appropriate level of log information in your application. For example, if you use the info level B, all log information (such as Debug) in your application that is below the info level will not be printed.
Iii. using log4j instances in Web projects
The above code describes the simple application of log4j, in fact, the use of log4j is so simple and convenient. Of course, in addition to the above configuration method, there are other, such as a Java EE application, in the Java EE application using log4j, you must first start the service load log4j configuration file initialization, can be done in Web. Xml.
1, the log4j use of the Web application is basically used: Create a new servlet, the servlet in the init function for log4j execution configuration. It is generally read into the configuration file. So 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. Here are two questions: first, need to know where the file is, second, the correct file type is required
3, configuration file location in Web. Xml to configure a param, the path is generally relative to the root directory
4, file types generally have two kinds, one is the property file of Java, the other is an XML file
Approximate contents of the configuration file: log4j can specify the lowest level of log level for output, and the output configuration format of log, each log can specify multiple output modes
(1) Create a Web project, the final catalog of the entire project is as follows
(2) the Web. XML is configured as follows:
<?xml version= "1.0" encoding= "UTF-8"?> <web-app xmlns:xsi= "Http://www.w3.org/2001/XMLSchema-instance" xmln s= "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-class> ;com.mucfc.log4jtestservlet</servlet-class> </servlet> <!--the servlet used to start log4jconfiglocation--> ; <servlet> <servlet-name>Log4JInitServlet</servlet-name> <SERVLET-CLASS>COM.MUCFC . Log4jinitservlet</servlet-class> <init-param> <param-name>log4j-properties-locatio N</param-name> <param-value>/WEB-INF/classes/log4j.properties</param-value> </i Nit-param> <load-on-startup>1</load-on-startup> </servlet> <servlet-mapping> <servlet- Name>log4jtestservlet</servlet-name> <url-pattern>/test</url-pattern> </servlet-mapp Ing> </web-app>
(3) configuration file log4j.properties
# # # set log levels # # Log4j.rootlogger = debug,stdout,d,e log4j.appender.stdout = Org.apache.log4j.ConsoleAppender Lo G4j.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 Lo G4j.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.apa Che.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) Web container to initialize the servlet
Log4jinitservlet.java
Package 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.apache.log4j.BasicConfigurator; Import Org.apache.log4j.PropertyConfigurator; /** * Servlet Implementation class Log4jinitservlet */@WebServlet ("/log4jinitservlet") public class Log4jinitservlet Extends HttpServlet {private static final long serialversionuid = 1L; /** * @see httpservlet#httpservlet () */public Log4jinitservlet () {super (); TODO auto-generated Constructor stub}/** * @see servlet#init (servletconfig) */public void I NIT (ServletConfig config) throws servletexception {System.out.println ("Log4jinitservlet is initializing LOG4J Log Setup Information "); String log4jlocation = Config.getinitparameter ("log4j-properties-location"); ServletContext sc = Config.getservletcontext (); if (log4jlocation = = null) {SYSTEM.ERR.PRINTLN ("* * * * has no log4j-properties-location initialized files, so use Basicconfigura Tor initialization "); Basicconfigurator.configure (); } else {String Webapppath = Sc.getrealpath ("/"); String Log4jprop = Webapppath + log4jlocation; File Yomamayesthissaysyomama = new file (Log4jprop); if (yomamayesthissaysyomama.exists ()) {System.out.println ("use:" + log4jprop+ "Initialize log setup Information"); Propertyconfigurator.configure (Log4jprop); } else {System.err.println ("* * *" + log4jprop + "File not found, so use basicconfigurator initialization"); Basicconfigurator.configure (); }} super.init (config); }/** * @see httpservlet#doget (httpservletrequEST request, httpservletresponse response) */protected void doget (HttpServletRequest request, Httpservletrespon SE response) throws Servletexception, IOException {//TODO auto-generated Method stub}/** * @se e Httpservlet#dopost (httpservletrequest request, httpservletresponse response) */protected void DoPost (Httpserv Letrequest request, HttpServletResponse response) throws Servletexception, IOException {//TODO auto-generated m Ethod stub}}
Call log Log4jtestservlet,java
Package COM.MUCFC; Import java.io.IOException; Import Javax.servlet.ServletConfig; 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.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 I NIT (ServletConfig config) throws servletexception {//TODO auto-generated Method stub}/** * @se E Httpservlet#doget (HttpServletRequest request, HttpServletResponse response) */protected void doget (HttpServletRequest request, Httpse Rvletresponse response) throws Servletexception, IOException {//Record debug level information Logger.debug ("This is D Ebug message. "); Log information for info level logger.info ("This is info message."); Records the error level information Logger.error ("This is the error message."); }/** * @see httpservlet#dopost (httpservletrequest request, httpservletresponse response) */protected void DoPost (HttpServletRequest request, httpservletresponse response) throws Servletexception, IOException {DoG ET (request,response); } }
The next step is to run and see the results:
Output Result:
Iv. using log4j in spring
Here to implement the Web project using spring to use log4j
(1) Connect the above project and then import the spring package
(2) Web. XML added
<!--setting up the 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 a watchdog thread is scanned for changes in the configuration file every 60 seconds, which makes it easy to change the location of the log storage- > <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 entire content is as follows:
<?xml version= "1.0" encoding= "UTF-8"?> <web-app xmlns:xsi= "Http://www.w3.org/2001/XMLSchema-instance" xmln s= "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-class> ;com.mucfc.log4jtestservlet</servlet-class> </servlet> <!--the servlet used to start log4jconfiglocation--> ; <!--<servlet> <servlet-name>Log4JInitServlet</servlet-name> <servlet-class& Gt;com.mucfc.log4jinitservlet</servlet-class> <init-param> <param-name>log4j-prope Rties-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> <!--Spring container loaded-<listener> <listener-class>org.spring Framework.web.context.contextloaderlistener</listener-class> </listener> <context-param> <param-name>contextConfigLocation</param-name> <PARAM-VALUE>CLASSPATH:APPLICATIONCONTEXT.XM L</param-value> </context-param> <!--set the root--<context-param> <par Am-name>webapprootkey</param-name> <param-value>webapp.root</param-value> </cont Ext-param> <context-param> <param-name>log4jConfigLocation</param-name> < param-value>/web-inf/Classes/log4j.properties</param-value> </context-param> <!--3000 means a watchdog thread is scanned for changes in configuration files every 60 seconds; This makes it easy to change the location of log storage-<context-param> <param-name>log4jRefreshInterval</param-name> <param-value>3000</param-value> </context-param> <listener> <list Ener-class>org.springframework.web.util.log4jconfiglistener</listener-class> </listener> </ Web-app>
The Log4jinitservlet.java here is the equivalent of 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/SCHEMA/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/context/ Spring-context-3.2.xsd "> </beans>
(3) The log is started with the spring window.
Once the program runs, it will automatically print the log
Log.log
Error.log is empty because it only prints information above the error level
Browser input Http://localhost:8080/LogLearning2/test
Then open the file
The most detailed tutorial for log4j use