The most detailed tutorial on log4j use

Source: Internet
Author: User
Tags print format stub log4j

The log is an integral part of the application software, and the Apache Open source project log4j is a powerful log component that provides easy logging. On the Apache website: jakarta.apache.org/log4j can download the latest version of the log4j package for free.
An example 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

### Set ### Log4j.rootlogger = debug,stdout,d,e ### output information to control lift ### log4j.appender.stdout = Org.apache.log4j.ConsoleAppender L
Og4j.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 error Level above log 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.apac He.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 me Ssage. ");  

        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.

Second, the basic use method of log4j

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 table),  
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, that is, the debug,info,warn,error,fatal  
%r output from the application boot to the output of the log information the number of milliseconds the output  
belongs to the class, usually the full name of the class  
%t output the thread name that generated the log event  
%n output A carriage return line break, Windows platform is "RN", UNIX platform is "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 to: October 18, 2002 22:10:28,921  
%l output Log event location, 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.
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 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" xml ns= "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-n ame> <servlet> <servlet-name>Log4JTestServlet</servlet-name> <servlet-c Lass>com.mucfc.log4jtestservlet</servlet-class> </servlet> <!--used to start the ser of log4jconfiglocation Vlet--> <servlet> <servlet-name>Log4JInitServlet</servlet-name> <servle T-class>com.mucfc.log4jinitservlet</servlet-class> <init-param> <param-name>l Og4j-properties-location</param-name> <param-value>/web-inf/classes/log4j.properties</param-v Alue> </init-param> <load-on-startup>1</load-on-startup> </servlet> <servlet-mapping&gt  
        ; <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.append Er.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.Th Reshold = 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.layo UT = 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 Log4jinitserv  

    Let 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 (ServletConfig 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 ("* * * * does not have log4j-properties-location initialization file, so use Basicconfigur  
            Ator 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) * * * prote  
        CTED void doget (HttpServletRequest request, httpservletresponse response) throws Servletexception, IOException { TODO auto-generated Method Stub}/** * @see httpservlet#dopost (httpservletrequest request, Httpser Vletresponse response) */protected void DoPost (HttpServletRequest request, httpservletresponse response) thro WS 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 Log4jtestserv  
    Let 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 D Oget (HttpServletRequest request, httpservletresponse response) throws Servletexception, IOException {//Record debug    
        Level of information Logger.debug ("This is the 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) * * * prot  
        ected void DoPost (HttpServletRequest request, httpservletresponse response) throws Servletexception, IOException {  
    Doget (Request,response); }  

}

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


Iv. using 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 </

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.