[Spring] Spring integrates log4j and javaweblog4j in Java Web projects.

Source: Internet
Author: User

[Spring] Spring integrates log4j and javaweblog4j in Java Web projects.

You may see this article in [Spring] Spring3.0.5 download, configuration, and Helloworld (click to open the link. If Spring does not integrate log4j directly, the following warning is displayed about Spring integrated log4j. This is annoying. On the one hand, I advocate High Cohesion and low coupling, and on the other hand, I am warned if I have not integrated log4j. The program written by our programmers is called "coupling", and Spring is called "integration ". Okay! You can only understand what log4j is and how Spring integrates log4j. There are two problems:

log4j:WARN No appenders could be found for logger (org.springframework.web.context.ContextLoader). log4j:WARN Please initialize the log4j system properly.
Since we have previously introduced a simple example of Spring in the Java project, log4j must be run in the Java Web project to make sense. You also need to understand how Spring runs on the Java Web project, how does Spring integrate log4j in the Java Web project.


1. Download Spring and Log4j

1. Do you need to have the jar packages of these two Java Web Components first? Otherwise, why? Spring has already discussed how to download Spring in [Spring] Spring3.0.5 download, configuration and Helloworld (click to open the link. Linux ). Apache is the same thing, in some later versions of Tomcat also integrated this thing, of course, you 'd better still in the WEB-INF \ lib directory to complete this package, so that your project can run on all Tomcat servers.


2. Create a Dynamic Web Project named SpringLog4j in Eclipse for JavaEE, and decompress the package of all the spring-framework-3.0.5.RELEASE-dependencies and all the Jar packages in the spring-framework-3.0.5.RELEASE \ dist, does not include the LIBD file, the apache-log4j-1.2.17 under the log4j-1.2.17.jar, copies to the WEB \ lib folder.


3. Your Eclipse for JavaEE is shown below. Web. xml, applicationContext. xml, log4j. properties under the WEB-INF directory and Log4j. jsp under the root directory are something we will write for a while.



Ii. configuration of Spring and Log4j

1. Web. xml

The first is the overall configuration location of the JavaWeb project. We need to declare the use of Spring and Log4j in it. It is worth noting that the Log4j configuration must be prior to Spring configuration. Otherwise, if Spring is started first, the Spring that must be integrated with Log4j will not be warned. Because Log4j has not been started yet, Spring cannot be found, he will give a warning as willfully as possible. Of course, you can set the priorities. However, if you start the file first and put it in front, isn't this file better-looking?

<? 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" version = "3.0"> <! -- Log4j configuration --> <listener-class> org. springframework. web. util. Log4jConfigListener </listener-class> </listener> <! -- Specify the directory where the Log4j configuration file is located. The default configuration is under the WEB-INF directory --> <context-param> <param-name> log4jConfigLocation </param-name> <param-value>/WEB-INF/log4j. properties </param-value> </context-param> <! -- Spring configuration --> <listener-class> org. springframework. web. context. ContextLoaderListener </listener-class> </listener> <! -- Specifies the directory where the configuration file of Spring Bean is located. The default configuration is under the WEB-INF directory --> <context-param> <param-name> contextConfigLocation </param-name> <param-value>/WEB-INF/applicationContext. xml </param-value> </context-param> </web-app>
2. log4j. properties

This guy's suffix is so long. What's your solution? It must be taken care of. They are all Linux-based masters. You can see that the suffix of the Windows configuration file is only an ini3 letter!

#log4j.rootLogger = [ level ] , appenderName, appenderName, ...log4j.rootLogger = all, console, R#Consolelog4j.appender.console = org.apache.log4j.ConsoleAppenderlog4j.appender.console.layout = org.apache.log4j.PatternLayoutlog4j.appender.console.layout.ConversionPattern = %-d{yyyy-MM-dd HH:mm:ss} [%c]-[%p] %m%n#Filelog4j.appender.R = org.apache.log4j.RollingFileAppenderlog4j.appender.R.File = c:/log.txtlog4j.appender.R.MaxFileSize = 500KBlog4j.appender.R.MaxBackupIndex = 1log4j.appender.R.layout = org.apache.log4j.PatternLayoutlog4j.appender.R.layout.ConversionPattern=%-d{yyyy-MM-dd HH:mm:ss} [%c]-[%p] - %m%n
You cannot add Chinese comments to this topic. # I can only write English things later. Where can I put my great tianchao program? I will not allow you to add a Chinese comment!

The first part is the overall configuration of log4j. all indicates that information of debug, info, error, and fatal types will be output. Generally, this parameter is not set to all. Here, we only want to show you the effect. The debug and info information is meaningless to us, and many internal file operations in the system will output the debug and info information flushed and flushed. The key is that the log files output to the disk will increase rapidly, wasting disk space. When I was playing SQL Server, I don't know how terrible that. ldb is?

Therefore, the first part is generally written:

log4j.rootLogger = ERROR, console, R
Only error and fatal error are output.

In the subsequent console, R represents the console and file output respectively. At the same time, the two outputs must be configured in the subsequent code.

Part 2 Console # Console
First, use a specific log4j package. There is nothing to say about it. The last sentence specifies the output format. After a while, compare the output results to understand what is going on.

Part 3 File # File

Log4j. appender. R. File = c:/log.txt indicates that all Web engineering error logs are exported to c:/log.txt. Do not output A. log suffix like those on the Internet. The key is to open it directly.

Then log4j. appender. r. maxFileSize = kbindicates that the maximum size of the log.txt file is KB. If the size exceeds this limit, a new file is automatically opened, while that of log4j. appender. r. maxBackupIndex = 1 indicates that at most one log file can be found in this project. If there is more, the new content will cover the old content, just like those of closed-circuit television cameras.

Log4j is finished here.

3. applicationContext. xml

Next is the part of Spring. Since Spring is not used at all this time, this applicationContext. xml can be written as follows:

<?xml version="1.0" encoding="UTF-8"?><beans xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"xmlns="http://www.springframework.org/schema/beans"xsi:schemaLocation="http://www.springframework.org/schema/beanshttp://www.springframework.org/schema/beans/spring-beans-3.0.xsd"></beans>
I deleted all the items that can be deleted.

4. Log4j. jsp

Finally, it is Log4j. jsp under the WebContent root directory. Write the following code in it. The entrance of the whole program is this place.

I don't want to do anything about Servlet anymore, just to let everyone know the key to the problem.

<% @ Page language = "java" contentType = "text/html; charset = UTF-8" pageEncoding = "UTF-8" import = "org. apache. log4j. logger "%> <% Logger. getLogger (this. getClass ()). fatal ("fatal error! "); Logger. getLogger (this. getClass (). error (" error message! "); Logger. getLogger (this. getClass (). info (" common information! "); Logger. getLogger (this. getClass (). debug (" debugging information! "); %>

Iii. Running results

Mount the Java Web project SpringLog4j to Tomcat, run it, and enter http: // localhost: 8080/SpringLog4j/Log4j in any browser. jsp. After the webpage is successfully loaded, return directly to Eclipse and get the following running result. If you enter a URL refresh once, the following result is output:


At the same time, your C drive generates a log.txt file with the following content. You can see that when the program is running, Spring runs out a lot of meaningless DEBUG, INFO, and TRACE information. For us, the last four sentences that are really useful. Therefore, we can understand why the above log4j. properties (this suffix is hard to remember, long, and despised again !) Generally, the first part only writes ERROR instead of all. This only outputs errors of the ERROR level or above, that is, ERROR and FATAL. You can also write it as a TRACE to output TRACE, ERROR, and FATAL information.

09:54:34 [org. springframework. web. context. contextLoader]-[INFO]-Root WebApplicationContext: initialization started2015-05-10 09:54:34 [org. springframework. web. context. support. xmlWebApplicationContext]-[INFO]-Refreshing Root WebApplicationContext: startup date [Sun May 10 09:54:34 CST 2015]; root of context hierarchy2015-05-10 09:54:34 [org. springframework. beans. factory. xml. xmlBeanDef InitionReader]-[INFO]-Loading XML bean definitions from ServletContext resource [/WEB-INF/applicationContext. xml] 09:54:34 [org. springframework. beans. factory. xml. defaultDocumentLoader]-[DEBUG]-Using JAXP provider [com.sun.org. apache. xerces. internal. jaxp. documentBuilderFactoryImpl] 09:54:34 [org. springframework. beans. factory. xml. pluggableSchemaResolver]-[TRACE]-Trying to r Esolve XML entity with public id [null] and system id [http://www.springframework.org/schema/beans/spring-beans-3.0.xsd#09:54:34 [org. springframework. beans. factory. xml. pluggableSchemaResolver]-[DEBUG]-Loading schema mappings from [META-INF/spring. schemas] 09:54:34 [org. springframework. beans. factory. xml. pluggableSchemaResolver]-[DEBUG]-Loaded schema mappings: {http://www.sp Http://www.springframework.org/schema/util/spring-util.xsd=org/springframework/beans/factory/xml/spring-util-3.0.xsd, http://www.springframework.org/schema/jms/spring-jms-3.0.xsd=org/springframework/jms/config/spring-jms-3.0.xsd, http://www.springframework.org/schema/task/spring-task.xsd=org/springfr Amework/scheduling/config/spring-task-3.0.xsd, http://www.springframework.org/schema/aop/spring-aop-3.0.xsd=org/springframework/aop/config/spring-aop-3.0.xsd, http://www.springframework.org/schema/aop/spring-aop-2.0.xsd=org/springframework/aop/config/spring-aop-2.0.xsd, http://www.springframework.org/schema/oxm/spring-oxm.xsd=org/springframework/oxm/config/spring-oxm-3.0.xsd, http://www.springfram Http://www.springframework.org/schema/beans/spring-beans.xsd=org/springframework/beans/factory/xml/spring-beans-3.0.xsd, http://www.springframework.org/schema/jee/spring-jee-2.5.xsd=org/springframework/ejb/config/spring-jee-2.5.xsd, http://www.springframework.org/schema/aop/spring-aop.xsd=org/sprin Gframework/aop/config/spring-aop-3.0.xsd, http://www.springframework.org/schema/beans/spring-beans-2.0.xsd=org/springframework/beans/factory/xml/spring-beans-2.0.xsd, http://www.springframework.org/schema/mvc/spring-mvc-3.0.xsd=org/springframework/web/servlet/config/spring-mvc-3.0.xsd, http://www.springframework.org/schema/beans/spring-beans-3.0.xsd=org/springframework/beans/factory/xml/spring-bea Ns-3.0.xsd, http://www.springframework.org/schema/task/spring-task-3.0.xsd=org/springframework/scheduling/config/spring-task-3.0.xsd, http://www.springframework.org/schema/tx/spring-tx-2.5.xsd=org/springframework/transaction/config/spring-tx-2.5.xsd, http://www.springframework.org/schema/context/spring-context-2.5.xsd=org/springframework/context/config/spring-context-2.5.xsd, http://www.springfram Http://www.springframework.org/schema/tool/spring-tool-3.0.xsd=org/springframework/beans/factory/xml/spring-tool-3.0.xsd, http://www.springframework.org/schema/tx/spring-tx.xsd=org/springframework/transaction/config/spring-tx-3.0.xsd, http://www.springframework.org/schema/tool/spring-tool-2.0.xsd=org/spr Ingframework/beans/factory/xml/spring-tool-2.0.xsd, http://www.springframework.org/schema/util/spring-util-2.5.xsd=org/springframework/beans/factory/xml/spring-util-2.5.xsd, http://www.springframework.org/schema/lang/spring-lang.xsd=org/springframework/scripting/config/spring-lang-3.0.xsd, http://www.springframework.org/schema/lang/spring-lang-2.5.xsd=org/springframework/scripting/config/spring-la Ng-2.5.xsd, http://www.springframework.org/schema/jee/spring-jee-3.0.xsd=org/springframework/ejb/config/spring-jee-3.0.xsd, http://www.springframework.org/schema/jee/spring-jee-2.0.xsd=org/springframework/ejb/config/spring-jee-2.0.xsd, http://www.springframework.org/schema/context/spring-context.xsd=org/springframework/context/config/spring-context-3.0.xsd, http://www.springframework.org/schema/je E/spring-jee.xsd = org/springframework/ejb/config/spring-jee-3.0.xsd, http://www.springframework.org/schema/jms/spring-jms-2.5.xsd=org/springframework/jms/config/spring-jms-2.5.xsd, http://www.springframework.org/schema/jms/spring-jms.xsd=org/springframework/jms/config/spring-jms-3.0.xsd, http://www.springframework.org/schema/aop/spring-aop-2.5.xsd=org/springframework/aop/config/spring-aop-2.5.xsd, Http://www.springframework.org/schema/mvc/spring-mvc.xsd=org/springframework/web/servlet/config/spring-mvc-3.0.xsd, http://www.springframework.org/schema/jdbc/spring-jdbc.xsd=org/springframework/jdbc/config/spring-jdbc-3.0.xsd, http://www.springframework.org/schema/tx/spring-tx-2.0.xsd=org/springframework/transaction/config/spring-tx-2.0.xsd, http://www.springframework.org/schema/tx/spring-tx-3.0. Xsd = org/springframework/transaction/config/spring-tx-3.0.xsd, http://www.springframework.org/schema/context/spring-context-3.0.xsd=org/springframework/context/config/spring-context-3.0.xsd, http://www.springframework.org/schema/tool/spring-tool.xsd=org/springframework/beans/factory/xml/spring-tool-3.0.xsd, http://www.springframework.org/schema/util/spring-util-3.0.xsd=org/springframework/beans/fac Spring-util-3.0.xsd, http://www.springframework.org/schema/lang/spring-lang-3.0.xsd=org/springframework/scripting/config/spring-lang-3.0.xsd, http://www.springframework.org/schema/util/spring-util-2.0.xsd=org/springframework/beans/factory/xml/spring-util-2.0.xsd, http://www.springframework.org/schema/lang/spring-lang-2.0.xsd=org/springframework/scripting/config/spring-lang-2.0.xsd, http :/ /Clusters 09:54:34 [org. springframework. beans. factory. xml. pluggableSchemaResolver]-[DEBUG]-Found XML schema [http://www.springframework.org/schema/beans/spring-beans-3.0.xsd] in classpath: org/springframework/beans/factory/xml/spring-beans-3.0.xsd2015-05-10 09:54:34 [org. springf Ramework. beans. factory. xml. defaultBeanDefinitionDocumentReader]-[DEBUG]-Loading bean definitions2015-05-10 09:54:34 [org. springframework. beans. factory. xml. xmlBeanDefinitionReader]-[DEBUG]-Loaded 0 bean definitions from location pattern [/WEB-INF/applicationContext. xml] 09:54:34 [org. springframework. web. context. support. xmlWebApplicationContext]-[DEBUG]-Bean factory for Root WebAppli CationContext: org. springframework. beans. factory. support. defaultListableBeanFactory @ 5eedf162: defining beans []; root of factory hierarchy2015-05-10 09:54:34 [org. springframework. web. context. support. xmlWebApplicationContext]-[DEBUG]-Unable to locate MessageSource with name 'messagesource': using default [org. springframework. context. support. delegatingMessageSource @ 314b0824] 2015-05-10 09:54:34 [or G. springframework. web. context. support. xmlWebApplicationContext]-[DEBUG]-Unable to locate ApplicationEventMulticaster with name 'applicationeventmulticaster': using default [org. springframework. context. event. simpleApplicationEventMulticaster @ 708a538f] 2015-05-10 09:54:34 [org. springframework. ui. context. support. uiApplicationContextUtils]-[DEBUG]-Unable to locate ThemeSource with name 'themesource ': Using default [org. springframework. ui. context. support. resourceBundleThemeSource @ 1fce66ba] 09:54:34 [org. springframework. beans. factory. support. defaultListableBeanFactory]-[INFO]-Pre-instantiating singletons in org. springframework. beans. factory. support. defaultListableBeanFactory @ 5eedf162: defining beans []; root of factory hierarchy2015-05-10 09:54:34 [org. springframework. web. context. Support. xmlWebApplicationContext]-[DEBUG]-Unable to locate LifecycleProcessor with name 'lifecycleprocessor ': using default [org. springframework. context. support. defaultLifecycleProcessor @ 7cbc2c83] 09:54:34 [org. springframework. beans. factory. support. defaultListableBeanFactory]-[DEBUG]-Returning cached instance of singleton bean 'lifecycleprocessor '2015-05-10 09:54:34 [org. springframew Ork. web. context. support. xmlWebApplicationContext]-[TRACE]-Publishing event in Root WebApplicationContext: org. springframework. context. event. contextRefreshedEvent [source = Root WebApplicationContext: startup date [Sun May 10 09:54:34 CST 2015]; root of context hierarchy] 09:54:34 [org. springframework. web. context. contextLoader]-[DEBUG]-Published root WebApplicationContext as ServletConte Xt attribute with name [org. springframework. web. context. webApplicationContext. ROOT] 09:54:34 [org. springframework. web. context. contextLoader]-[INFO]-Root WebApplicationContext: initialization completed in 230 ms2015-05-10 09:54:48 [org. apache. jsp. log4j_jsp]-[FATAL]-FATAL error! 09:54:48 [org. apache. jsp. Log4j_jsp]-[ERROR]-ERROR message! 09:54:48 [org. apache. jsp. Log4j_jsp]-[INFO]-General information! 09:54:48 [org. apache. jsp. Log4j_jsp]-[DEBUG]-debugging information!

Iv. Summary

Generally, Log4j is not directly written in log4j. jsp like this. Usually in the catch in the try-catch exception structure, maybe some operation files and key data in the database are directly presented to the programmer. The programmer looks at log.txt, just like the security guard is free to watch closed-circuit television to determine whether your WEB project is abnormal. It can be part of system O & M.

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.