Log4j 学习笔记(五)SpringMVC4整合Log4j

本节,将分享如何在一个SpringMVC web应用中整合log4j记录系统日志。

更多精彩请阅读 东陆之滇的csdn博客:http://blog.csdn.net/zixiao217

准备工作(根据自己的要求调整)

  • Log4j 1.2.17
  • Spring 4.2.5.RELEASE
  • Maven 3
  • Tomcat 9
  • Eclipse neon版本

注意
默认情况下,Spring(Spring-core)使用JCL(commons-logging)记录日志,JCL在运行时可以发现其他classpath下的日志框架

集成log4j,你需要:

  • 将log4j.jar添加到classpath中
  • 在classpath下创建一个log4j.propertieslog4j.xml文件,如果使用maven风格的结构,放置在src/main/resources目录下

1. 工程目录

Log4j 学习笔记(五)SpringMVC4整合Log4j_第1张图片

2. 项目依赖

完整的pom.xml

<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
    xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
    <modelVersion>4.0.0modelVersion>

    <groupId>org.byron4jgroupId>
    <artifactId>spring-mvc-log4jartifactId>
    <version>1.0.0-SNAPSHOTversion>
    <packaging>warpackaging>

    <name>spring-mvc-log4jname>
    <url>http://blog.csdn.net/zixiao217url>

    <properties>
        <project.build.sourceEncoding>UTF-8project.build.sourceEncoding>
        <spring.version>4.2.5.RELEASEspring.version>
        <log4j.version>1.2.17log4j.version>
    properties>

    <dependencies>

        
        <dependency>
            <groupId>org.springframeworkgroupId>
            <artifactId>spring-webmvcartifactId>
            <version>${spring.version}version>
        dependency>

        
        <dependency>
            <groupId>log4jgroupId>
            <artifactId>log4jartifactId>
            <version>${log4j.version}version>
        dependency>


        
        <dependency>
            <groupId>javax.servletgroupId>
            <artifactId>servlet-apiartifactId>
            <version>2.5version>
        dependency>


        <dependency>
            <groupId>junitgroupId>
            <artifactId>junitartifactId>
            <version>3.8.1version>
            <scope>testscope>
        dependency>
    dependencies>

    <build>
        <plugins>
            <plugin>
                <groupId>org.apache.maven.pluginsgroupId>
                <artifactId>maven-compiler-pluginartifactId>
                <version>3.5.1version>
                <configuration>
                    <source>1.8source>
                    <target>1.8target>
                configuration>
            plugin>
        plugins>
    build>
project>

3. log4j.properties


log4j.rootLogger=info, stdout, file


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=%d{yyyy-MM-dd HH:mm:ss} %-5p %c{1}:%L - %m%n


log4j.appender.file=org.apache.log4j.RollingFileAppender
log4j.appender.file.File=E:\\eclipse-log\spring-mvc-log4j.log
log4j.appender.file.MaxFileSize=5MB
log4j.appender.file.MaxBackupIndex=10
log4j.appender.file.layout=org.apache.log4j.PatternLayout
log4j.appender.file.layout.ConversionPattern=%d{yyyy-MM-dd HH:mm:ss.S} %-5p %c{1}:%L - %m%n

4. web.xml

<web-app xmlns="http://java.sun.com/xml/ns/javaee"
    xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
    xsi:schemaLocation="http://java.sun.com/xml/ns/javaee
    http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd"
    version="2.5">

    <display-name>Gradle + Spring MVC Hello World + XMLdisplay-name>
    <description>Spring MVC web applicationdescription>
    <welcome-file-list>
        <welcome-file>
            /index.jsp
        welcome-file>
    welcome-file-list>

    
    <servlet>
        <servlet-name>hello-dispatcherservlet-name>
        <servlet-class>
                        org.springframework.web.servlet.DispatcherServlet
                servlet-class>
        <init-param>
            <param-name>contextConfigLocationparam-name>
            <param-value>/WEB-INF/spring-mvc-config.xmlparam-value>
        init-param>
        <load-on-startup>1load-on-startup>
    servlet>

    <servlet-mapping>
        <servlet-name>hello-dispatcherservlet-name>
        <url-pattern>/url-pattern>
    servlet-mapping>

    
    <listener>
        <listener-class>
                  org.springframework.web.context.ContextLoaderListener
                listener-class>
    listener>

    <context-param>
        <param-name>contextConfigLocationparam-name>
        <param-value>/WEB-INF/spring-mvc-config.xmlparam-value>
    context-param>

web-app>

5. SpringMVC配置文件

spring-mvc-config.xml:

<beans xmlns="http://www.springframework.org/schema/beans"
    xmlns:context="http://www.springframework.org/schema/context"
    xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
    xmlns:mvc="http://www.springframework.org/schema/mvc"
    xsi:schemaLocation="
        http://www.springframework.org/schema/beans
        http://www.springframework.org/schema/beans/spring-beans.xsd
        http://www.springframework.org/schema/mvc
        http://www.springframework.org/schema/mvc/spring-mvc.xsd
        http://www.springframework.org/schema/context
        http://www.springframework.org/schema/context/spring-context.xsd ">

    <context:component-scan base-package="org.byron4j" />

    <bean class="org.springframework.web.servlet.view.InternalResourceViewResolver">
        <property name="viewClass" value="org.springframework.web.servlet.view.JstlView"/>
        <property name="prefix" value="/WEB-INF/views/jsp/" />
        <property name="suffix" value=".jsp" />
    bean>

    <mvc:resources mapping="/resources/**" location="/resources/" />

    <mvc:annotation-driven />

beans>

6. 编写SpringMVC Controller + logging

WelcomeController.java类:

package org.byron4j.spring_mvc_log4j;

import org.apache.log4j.Logger;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.bind.annotation.RestController;

/**
 * Hello world!
 *
 */
@RestController
public class WelcomeController 
{
    private static Logger logger = Logger.getLogger(WelcomeController.class);

    @RequestMapping("/welcome")
    @ResponseBody
    public String getAppName(){
        logger.info("访问首页");
        return "

SpringMVC integrate log4j - a demo

"
; } }

7. 运行SpringMVC web应用

在浏览器访问http://localhost:8080/spring-mvc-log4j/welcome,界面:
这里写图片描述
控制台输出:2016-10-27 00:33:07 INFO WelcomeController:20 - 访问首页
在指定的目录E:\eclipse-log下生成了日志文件spring-mvc-log4j.log,打开看到内容:

2016-10-27 00:44:50.489 INFO  ContextLoader:305 - Root WebApplicationContext: initialization started
2016-10-27 00:44:50.676 INFO  XmlWebApplicationContext:578 - Refreshing Root WebApplicationContext: startup date [Thu Oct 27 00:44:50 CST 2016]; root of context hierarchy
2016-10-27 00:44:50.771 INFO  XmlBeanDefinitionReader:317 - Loading XML bean definitions from ServletContext resource [/WEB-INF/spring-mvc-config.xml]
2016-10-27 00:44:51.660 INFO  SimpleUrlHandlerMapping:341 - Mapped URL path [/resources/**] onto handler 'org.springframework.web.servlet.resource.ResourceHttpRequestHandler#0'
2016-10-27 00:44:51.758 INFO  RequestMappingHandlerMapping:534 - Mapped "{[/welcome]}" onto public java.lang.String org.byron4j.spring_mvc_log4j.WelcomeController.getAppName()
2016-10-27 00:44:51.856 INFO  RequestMappingHandlerAdapter:532 - Looking for @ControllerAdvice: Root WebApplicationContext: startup date [Thu Oct 27 00:44:50 CST 2016]; root of context hierarchy
2016-10-27 00:44:51.932 INFO  RequestMappingHandlerAdapter:532 - Looking for @ControllerAdvice: Root WebApplicationContext: startup date [Thu Oct 27 00:44:50 CST 2016]; root of context hierarchy
2016-10-27 00:44:52.29 INFO  ContextLoader:345 - Root WebApplicationContext: initialization completed in 1536 ms
2016-10-27 00:44:52.53 INFO  DispatcherServlet:488 - FrameworkServlet 'hello-dispatcher': initialization started
2016-10-27 00:44:52.57 INFO  XmlWebApplicationContext:578 - Refreshing WebApplicationContext for namespace 'hello-dispatcher-servlet': startup date [Thu Oct 27 00:44:52 CST 2016]; parent: Root WebApplicationContext
2016-10-27 00:44:52.58 INFO  XmlBeanDefinitionReader:317 - Loading XML bean definitions from ServletContext resource [/WEB-INF/spring-mvc-config.xml]
2016-10-27 00:44:52.128 INFO  SimpleUrlHandlerMapping:341 - Mapped URL path [/resources/**] onto handler 'org.springframework.web.servlet.resource.ResourceHttpRequestHandler#0'
2016-10-27 00:44:52.139 INFO  RequestMappingHandlerMapping:534 - Mapped "{[/welcome]}" onto public java.lang.String org.byron4j.spring_mvc_log4j.WelcomeController.getAppName()
2016-10-27 00:44:52.156 INFO  RequestMappingHandlerAdapter:532 - Looking for @ControllerAdvice: WebApplicationContext for namespace 'hello-dispatcher-servlet': startup date [Thu Oct 27 00:44:52 CST 2016]; parent: Root WebApplicationContext
2016-10-27 00:44:52.166 INFO  RequestMappingHandlerAdapter:532 - Looking for @ControllerAdvice: WebApplicationContext for namespace 'hello-dispatcher-servlet': startup date [Thu Oct 27 00:44:52 CST 2016]; parent: Root WebApplicationContext
2016-10-27 00:44:52.239 INFO  DispatcherServlet:507 - FrameworkServlet 'hello-dispatcher': initialization completed in 185 ms
2016-10-27 00:44:58.298 INFO  WelcomeController:20 - 访问首页

结束了。这里又搭了一遍SpringMVC配置哦。。。

你可能感兴趣的:(【Log4j】)