The use of log4j in the Javaweb project

Source: Internet
Author: User

The log4j configuration file is described in the preceding article, and today describes how to use log4j in a common Javaweb project.

In the daily development process, the log is used very frequently, we can use the log to track the program errors, program runtime output parameters, etc., in many cases may use SYSTEM.OUT.PRINTLN () This method, but there is a more concise way, that is, using the log framework, Let's take a look at log4j today. How this log framework is used in javaweb classes.

One, log4j configuration file

We have to use log4j must have log4j configuration file, the previous article mentions that there are two types of configuration file in Log4j, one is XML and the other is properties, I prefer to use the latter, which is also used here. The configuration file is as follows,

# # # set log Levels # # # Log4j.rootlogger=Info,stdout,d # #对com. All error level logs under the MUCFC package are output
LOG4J.LOGGER.COM.MUCFC=Errorlog4j.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.logLog4j.appender.d.append =falseLog4j.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


From the top of the configuration file can be seen for the entire project, log interface for info, the COM.MUCFC package is configured with the error level, the output destination is two: stdout (console), D (file, output log minimum level of debug), This means that if there are logger.debug (), Logger.info (), Logger.warn (), Logger.error () in the class, the output will be as below.

Second, initialize the log4j configuration file

The first step above we configured the log4j configuration file, below is the initialization of the log4j. We built a normal Javaweb project here, and didn't use any of the frameworks (e.g., spring, and spring, as explained in the next article), so how do we load the configuration file when the project just starts? We know that there are filters in the Web project, listener they will be initialized at the start of the project, filter is not suitable for filtering here, listener is listening, here can use listener, there is a more use of the more, that is the servlet , this thing we used a lot in the development, and can specify the initialization order, here we use the servlet, and specify the order of initialization is 1,

 PackageCOM.MUCFC; ImportJava.io.File;Importjava.io.IOException;ImportJavax.servlet.Servlet;ImportJavax.servlet.ServletConfig;ImportJavax.servlet.ServletContext;Importjavax.servlet.ServletException;ImportJavax.servlet.http.HttpServlet;Importjavax.servlet.http.HttpServletRequest;ImportJavax.servlet.http.HttpServletResponse;ImportOrg.apache.log4j.BasicConfigurator;ImportOrg.apache.log4j.PropertyConfigurator;/*** Servlet Implementation class Log4jinitservlet*/   Public classLog4jinitservletextendsHttpServlet {Private Static Final LongSerialversionuid = 1L; /**      * @seeHttpservlet#httpservlet ()*/       PublicLog4jinitservlet () {Super(); //TODO auto-generated Constructor stub    }      /**      * @seeservlet#init (servletconfig)*/       Public voidInit (servletconfig config)throwsservletexception {System.out.println ("Log4jinitservlet Initializing log4j log setup Information"); String log4jlocation= Config.getinitparameter ("Log4j-properties-location"); ServletContext SC=Config.getservletcontext (); String Str= (String) sc.getinitparameter ("Test"); System.out.println ("STR:" +str); if(Log4jlocation = =NULL) {System.err.println ("* * * No log4j-properties-location initialized files, so use Basicconfigurator initialization");          Basicconfigurator.configure (); } Else{String Webapppath= Sc.getrealpath ("/"); String Log4jprop= Webapppath +log4jlocation; File Yomamayesthissaysyomama=NewFile (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); }      /**      * @seeHttpservlet#doget (httpservletrequest request, httpservletresponse response)*/      protected voidDoget (HttpServletRequest request, httpservletresponse response)throwsservletexception, IOException {//TODO auto-generated Method Stub    }      /**      * @seeHttpservlet#dopost (httpservletrequest request, httpservletresponse response)*/      protected voidDoPost (HttpServletRequest request, httpservletresponse response)throwsservletexception, IOException {//TODO auto-generated Method Stub    }  }

As can be seen from the above, this servlet reads the path of the log4j from the initialization parameters of the servlet and then uses Propertyconfigurator.configure (Log4jprop); To initialize, the following is Web. XML,

<?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_2_5.xsd "id=" webapp_id "version=" 2.5 "> <display-name>log4j</ display-name> <welcome-file-list> <welcome-file>index.html</welcome-file> </welcome-file- list> <servlet> <servlet-name>Log4JTestServlet</servlet-name> <servlet-class>com.mucfc.log4jtestservlet</servlet-class> </servlet> <servlet> <servlet-name>Log4JInitServlet</servlet-name> <servlet-class>com.mucfc.log4jinitservlet</servlet-class> <init-param> <param-name>log4j-properties-location</param-name> <param-value>log 4j.properties</param-value> </init-param> <load-on-startup>1</load-on-startup> </ Servlet></web-app>

Using the Log4j-properties-location parameter name, the configured value is log4j.properties, I put the configuration file under Web-cotent, that is, under the root path,

Third, testing

I'm testing the servlet here, calling the Log4j log output feature when requesting a servlet.

 Packagecom.test;Importjava.io.IOException;Importjavax.servlet.ServletException;ImportJavax.servlet.http.HttpServlet;Importjavax.servlet.http.HttpServletRequest;ImportJavax.servlet.http.HttpServletResponse;ImportOrg.apache.log4j.Logger;/*** Servlet Implementation class Myfirsttest*/ Public classMyfirsttestextendsHttpServlet {Private Static Final LongSerialversionuid = 1L; PrivateLogger Logger=logger.getlogger ( This. GetClass ()); /**     * @seeHttpservlet#httpservlet ()*/     Publicmyfirsttest () {Super(); //TODO auto-generated Constructor stub    }    /**     * @seeHttpservlet#doget (httpservletrequest request, httpservletresponse response)*/    protected voidDoget (HttpServletRequest request, httpservletresponse response)throwsservletexception, IOException {//TODO auto-generated Method StubDoPost (Request,response); }    /**     * @seeHttpservlet#dopost (httpservletrequest request, httpservletresponse response)*/    protected voidDoPost (HttpServletRequest request, httpservletresponse response)throwsservletexception, IOException {//TODO auto-generated Method StubLogger.info ("This is my info message"); Logger.debug ("This is my debug message"); Logger.warn ("This is my warn message"); Logger.error ("This is my error message"); }}

First get a Log object Logger, using the Logger Logger=logger.getlogger (This.getclass ()), and then call the Debug (), info (), warn (), error () method, The log is printed, according to the configuration file, the corresponding log will be printed, we here the entire project's log level is defined as info, then the content of the three methods of info (), warn (), error () will be printed in the console.

To summarize, use log4j in a common Javaweb project, and the next article will show you how to use it in spring projects.

Welcome to the point where it's not right

Thank you

The use of log4j in the Javaweb project

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.