Java log4j Detailed Tutorial _java

Source: Internet
Author: User
Tags aop html form print format stub java web log4j

One: log4j Introduction to Learning

Log4j is an open source project for Apache, by using log4j, we can control the destination of log information delivery is console, file, GUI component, even interface server, NT Event recorder, UNIX syslog daemon, etc. We can also control the output format of each log, and by defining the level of each log information, we can control the log generation process more carefully. Most interesting of all, these can be configured flexibly with a single configuration file without the need to modify the applied code.

In addition, by log4j other language interfaces, you can use log4j in C, C + +,. Net, and Pl/sql programs, and its syntax and usage, as in Java programs, make a unified and consistent Log component module for a multilingual distributed system. Also, by using a variety of third-party extensions, you can easily integrate log4j into Java EE, Jini, and even SNMP applications.

Ii. examples of Getting Started

1. Create a new Java project, import package Log4j-1.2.17.jar, the entire project final catalogue is as follows

2, SRC peers to create and set log4j.properties

### Settings ###
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 debug level above log 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 the log 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 the log content

Package COM.MUCFC;
Import Org.apache.log4j.Logger;
/**
 * @author Linbingwen
 *@2015 year 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 m Essage. "); 
 Record the debug level information 
 logger.debug ("This is debug message."); 
 Record info level information 
 logger.info ("This is info."); 
 Record error level information 
 logger.error ("This is error message."); 
 } 

4. Output result

(1) First is the information of the console

(2) again to see the output of the file

as follows, it is found that the required output to the corresponding document.

Three, log4j basic use method

Log4j is composed of three important components: priority of log information, output destination of log information, and output format of log information. Log information priority from high to low have 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 file, and the output format controls the display of the log information.

2.1. Define configuration file

You can actually configure the LOG4J environment in your code without using a 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 for Java attribute files (key = value). Here's how to use the Java attribute file as a configuration file:
1. Configure the root logger, whose syntax is:

Log4j.rootlogger = [level], Appendername, Appendername, ...
Where level is the priority of logging, divided into off, FATAL, ERROR, WARN, INFO, DEBUG, all, or levels you define. LOG4J recommends using only four levels, from high to low, respectively, for error, WARN, INFO, and DEBUG. By the level defined here, you can control the switch to log information at the appropriate level in your application. For example, if the info level is defined here, all debug-level log information in the application will not be printed. Appendername refers to where B log information is exported. You can specify multiple output destinations at the same time.

2. Configuration log information output destination Appender, its 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 appender:

Org.apache.log4j.ConsoleAppender (console),
Org.apache.log4j.FileAppender (file),
Org.apache.log4j.DailyRollingFileAppender (a log file is generated 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 to any specified place in streaming format)

3. Configure the format (layout) of the 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

Of these, the log4j provides layout with several e:

Org.apache.log4j.HTMLLayout (layout in HTML form),
Org.apache.log4j.PatternLayout (You can specify layout patterns flexibly),
Org.apache.log4j.SimpleLayout (The level and information string that contains the log information),
Org.apache.log4j.TTCCLayout (contains information about the time, thread, category, and so on that the log was generated)
LOG4J uses a print format similar to the printf function in c to format the log information, printing parameters 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 it takes to boot to output the log information
The class to which the%c output belongs, usually the full name of the class in which it is located
%t output The name of the thread that generated the log event
%n output a carriage return line feed, Windows platform "RN", UNIX platform "n"
%d output log point-in-time date or time, the default format is ISO8601, you can also specify the format after, such as:%d{yyy MMM dd hh:mm:ss,sss}, output similar: October 18, 2002 22:10:28,921
%l the location where the output 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, the use of log4j in the code

1. Get the Recorder

Using log4j, the first step is to get the logger, which will be responsible for controlling log information. Its syntax is:

public static Logger GetLogger (String name)

Gets the logger by the specified name and, if necessary, creates a new logger for that 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 uses the default log4j environment.
Propertyconfigurator.configure (String configfilename): Reads a configuration file written using a Java-specific attribute file.
Domconfigurator.configure (String filename): Reads a configuration file in XML form.
3. Insert record information (format log information)

When the two necessary steps are completed, you can easily insert any of the different priority logging statements into the places 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. Log levels are divided from high to Low:

A:off the highest level, to turn off all log records.
B:fatal that each serious error event will cause the application to exit.
C:error that although an error event occurs, it still does not affect the continued operation of the system.
D:warm indicates a potential error condition.
E:info generally and at a coarse-grained level, emphasize the full application operation.
F:debug is typically used at fine-grained levels and is very helpful for debugging applications.
G:all lowest level to open all log records.

The above levels are defined in the Org.apache.log4j.Level class. Log4j only recommends 4 levels, from high to low, respectively, Error,warn,info and Debug. By using the logging level, you can control the output of the corresponding level of log information in your application. For example, if you use the info level of B, all log information below the info level in your application, such as debug, will not be printed.

Iv. 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 methods, 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 carried out in the web.xml.

1, the log4j use of Web applications are basically: Create a servlet, this 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, and two, need the correct file type

3, the configuration file location in Web.xml Configure a param, the path is generally relative to the Web root directory

4, the file type generally has two kinds, one is the Java property file, the other is the XML file

General contents of the configuration file: log4j can specify the lowest level of log output and the output configuration of log, each log can specify multiple output modes

(1) Create the Web project, the final catalogue of the project 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-class> Com.mucfc.log4jtestservlet</servlet-class> </servlet> <!--the servlet--> to start log4jconfiglocation &L T;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.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 that is initialized when the Web container arrives

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 Log4jinitservle 
 T 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 init (servletconf 
 IG config) throws servletexception {System.out.println ("Log4jinitservlet Initializing log4j Log settings information"); String LOG4JLocation = Config.getinitparameter ("log4j-properties-location"); 
 ServletContext sc = Config.getservletcontext (); 
 if (log4jlocation = null) {SYSTEM.ERR.PRINTLN ("* * * No log4j-properties-location initialization file, so use basicconfigurator 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+ "initialization log settings 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 (H Ttpservletrequest request, HttpServletResponse response) throws Servletexception, IOException {//TODO auto-generated m Ethod stub}/** * @see HTtpservlet#dopost (HttpServletRequest request, httpservletresponse response) * * protected void DoPost (Httpservletreque 
St request, httpservletresponse Response) throws 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.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 Log4jtestservle 
 T 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 (servletconf IG config) throws servletexception {//TODO auto-generated Method stub}/** * @see httpservlet#doget (httpservlet Request request, HttpServletResponse response) * * protected void doget (HttpServletRequest request, httpservletresponse response) throws Servletexception, IOException {// 
 Record the debug level information Logger.debug ("This is debug message."); 
 Record info level information Logger.info ("This is info."); 
 Record 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 {doget (Request, 
 Response); } 
}

The next step is to run, to see the results:

Output results:

V. Use LOG4J in spring

Here to implement a Web project using spring to use the log4j

(1) Connect the above project and then import the spring package

(2) Web.xml increase

<!--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 indicates that a watchdog thread scans the configuration file for every 60 seconds, making it easier for the log storage location to change- > 
<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 contents are 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-class>c 
Om.mucfc.log4jtestservlet</servlet-class> </servlet> <!--a servlet to start log4jconfiglocation--> <!--<servlet> <servlet-name>Log4JInitServlet</servlet-name> <servlet-class> Com.mucfc.log4jinitservlet</servlet-class> <init-param> <param-name>log4j-properties-location& 
  Lt;/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 load--> <listener> <listener-class>org.s Pringframework.web.context.contextloaderlistener</listener-class> </listener> <context-param> & Lt;param-name>contextconfiglocation</param-name> <param-value>classpath:applicationcontext.xml </param-value> </context-param> <!--setting root directory--> <context-param> <param-name>webappro Otkey</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 indicates that a watchdog thread scans the profile 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> <liste Ner> <listener-class>org.springframework.web.util.Log4jConfigListener</listener-class> </ Listener> </web-app>

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/beans
http://www.springframework.org/schema/beans/spring-beans-3.2.xsd
HTTP://WWW.SPRINGFRAMEWORK.ORG/SCHEMA/AOP
http://www.springframework.org/schema/aop/spring-aop-3.2.xsd
Http://www.springframework.org/schema/context
   http://www.springframework.org/schema/context/ Spring-context-3.2.xsd "> 
</beans>

(3) So the log starts with the Spring window.

Once the program is running, 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

And then open the file

About the Java log4j Detailed tutorial to this end, the following article will introduce you to the Java Web log4j configuration and in the Web project configuration log4j skills, interested friends continue to focus on the site Oh.

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.