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

2023-05-04 20:21:36 浏览数 (2)

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

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

  • 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. 工程目录

2. 项目依赖

完整的pom.xml

代码语言:javascript复制
<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.0</modelVersion>

    <groupId>org.byron4j</groupId>
    <artifactId>spring-mvc-log4j</artifactId>
    <version>1.0.0-SNAPSHOT</version>
    <packaging>war</packaging>

    <name>spring-mvc-log4j</name>
    <url>http://blog.csdn.net/zixiao217</url>

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

    <dependencies>

        <!-- Spring -->
        <dependency>
            <groupId>org.springframework</groupId>
            <artifactId>spring-webmvc</artifactId>
            <version>${spring.version}</version>
        </dependency>

        <!-- Log4j -->
        <dependency>
            <groupId>log4j</groupId>
            <artifactId>log4j</artifactId>
            <version>${log4j.version}</version>
        </dependency>


        <!-- https://mvnrepository.com/artifact/javax.servlet/servlet-api -->
        <dependency>
            <groupId>javax.servlet</groupId>
            <artifactId>servlet-api</artifactId>
            <version>2.5</version>
        </dependency>


        <dependency>
            <groupId>junit</groupId>
            <artifactId>junit</artifactId>
            <version>3.8.1</version>
            <scope>test</scope>
        </dependency>
    </dependencies>

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

3. log4j.properties

代码语言:javascript复制
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-logspring-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

代码语言:javascript复制
<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   XML</display-name>
    <description>Spring MVC web application</description>
    <welcome-file-list>
        <welcome-file>
            /index.jsp
        </welcome-file>
    </welcome-file-list>

    <!-- For web context -->
    <servlet>
        <servlet-name>hello-dispatcher</servlet-name>
        <servlet-class>
                        org.springframework.web.servlet.DispatcherServlet
                </servlet-class>
        <init-param>
            <param-name>contextConfigLocation</param-name>
            <param-value>/WEB-INF/spring-mvc-config.xml</param-value>
        </init-param>
        <load-on-startup>1</load-on-startup>
    </servlet>

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

    <!-- For root context -->
    <listener>
        <listener-class>
                  org.springframework.web.context.ContextLoaderListener
                </listener-class>
    </listener>

    <context-param>
        <param-name>contextConfigLocation</param-name>
        <param-value>/WEB-INF/spring-mvc-config.xml</param-value>
    </context-param>

</web-app>

5. SpringMVC配置文件

spring-mvc-config.xml:

代码语言:javascript复制
<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类:

代码语言:javascript复制
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 "<h1>SpringMVC integrate  log4j - a demo</h1>";
    }
}

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,打开看到内容:

代码语言:javascript复制
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配置哦。。。

0 人点赞