Javaweb Learning Notes log4j using the tutorial __java

Source: Internet
Author: User
Tags aop stub log4j

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

### 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 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.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 mess Age. ");  

    Record the debug level information  
    logger.debug ("This is debug message.");  
    Record info level information  
    logger.info ("This is info.");  
    Record the information logger.error the error level  
    ("This is the error message.");  
}  

}
4. Output result

(1) First is the information of the console

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,stdo Ut,d,e log4j.appender.stdout = Org.apache.log4j.ConsoleAppender Log4j.appender.stdout.Target = System.out Log4j.app Ender.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 = Tru E Log4j.appender.e.threshold = ERROR log4j.appender.e.layout = org.apache.log4j.PatternLayout Log4j.appender.e.layo Ut. Conversionpattern =%-d{yyyy-mm-dd HH:mm:ss} [%t:%r]-[%p]%m%n (4) The servlet Log4jinitservlet.java pack initialized when the Web container  

Age 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 is 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+ "Initialize 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 PA  Ckage 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 doget (httpservletrequ EST request, httpservletresponse response) throws Servletexception, IOException {//Logging debug Level information lo    
        Gger.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) * * * prot  
        ected void DoPost (HttpServletRequest request, httpservletresponse response) throws Servletexception, IOException {  
    Doget (Request,response); }  

}

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 Add <!--set root--> <context-param> <param-name>webapp    

   Rootkey</param-name> <param-value>webapp.root</param-value> </context-param> <context-param> <param-name>log4jConfigLocation</param-name> <param-value>/web-in F/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> <listener> <listener-clas S>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> & Lt;servlet-name>log4jtestservlet</servlet-name> <servlet-class>com.mucfc.log4jtestservlet</se   
        Rvlet-class> </servlet> <!--to start log4jconfiglocation servlet--> <!--<servlet> <servlet-name>Log4JInitServlet</servlet-name> <servlet-class>com.mucfc.log4jinitser Vlet</servlet-class> <init-param> <param-name>log4j-properties-location</para M-name> <param-value>/WEB-INF/classes/log4j.properties</param-value> </init-para m> <load-on-startup>1</load-on-startup> </servlet>--> &LT;SERVLET-MAPPING&G  
        T <servlet-name&gT Log4jtestservlet</servlet-name> <url-pattern>/test</url-pattern> </servlet-mapping&gt   

        ; <!--Spring container load--> <listener> &LT;LISTENER-CLASS&GT;ORG.SPRINGFRAMEWORK.WEB.CONTEXT.CONTEXTL oaderlistener</listener-class> </listener> <context-param> <param-name>conte  
    Xtconfiglocation</param-name> <param-value>classpath:applicationContext.xml</param-value> </context-param> <!--set root directory--> <context-param> <param-name>webapproot    

    Key</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 to open a watchdog thread every 60 seconds to sweep A description of the configuration filechange; 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 the Log4jinitservlet.java is equivalent to 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:schemaloc ation= "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>

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.