SpringMVC4整合Log4j

SpringMVC4整合Log4j

2016年10月27日 00:47:28

阅读数:9867

本节,将分享如何在一个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. 工程目录

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.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


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 + 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:

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

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配置哦。。。

原文地址:https://www.cnblogs.com/xiaolei2017/p/9297184.html

时间: 2024-08-25 16:03:42

SpringMVC4整合Log4j的相关文章

Spring整合log4j日志组件

PHP转Java有一段时间了,最近在学习Spring的一些组件安装.配置及使用.今天学习了log4j作为项目日志操作组件为web开发节省了大量在项目过程中记录日志及日志输送存储的工作. Log4j是Apache的一个开放源代码项目,通过使用Log4j,控制日志信息输送的目的地可以为控制台.文件.数据库.GUI组件.甚至是套接口服务器.NT的事件记录器.UNIX Syslog守护进程等:可以控制每一条日志的信息内容和信息输出格式:通过定义每一条日志信息的级别,我们能够更加细致地控制日志的生成过程:

【Spring】Spring在JavaWeb工程中整合log4j

在<[Spring]Spring3.0.5的下载.配置与Helloworld>(点击打开链接)一文各位已经可能看到了.如果Spring不整合log4j直接启动,则会出现如下关于Spring整合log4j的警告.这个挺烦人的,一方面自己提倡高内聚,低耦合,另一方面,自己没有整合log4j就提出警告.我们程序猿写出来的程序就叫做"耦合",它Spring就叫做"整合".好吧!你只能同时搞明白,log4j是个什么鬼东西,Spring怎么整合log4j,两个问题:

Spring整合log4j日志组件(转)

Log4j是Apache的一个开放源代码项目,通过使用Log4j,控制日志信息输送的目的地可以为控制台.文件.数据库.GUI组件.甚至是套接口服务器.NT的事件记录器.UNIX Syslog守护进程等:可以控制每一条日志的信息内容和信息输出格式:通过定义每一条日志信息的级别,我们能够更加细致地控制日志的生成过程:甚至还可以在不需要修改业务逻辑代码.重启web服务,只需要通过一个修改配置文件就可以实现控制项目的日志动作. 首先,日志的级别有:OFF .FATAL .ERROR.WARN.INFO.

Mybatis3+Spring4+SpringMVC4 整合【转】

首先在整合这个框架的时候,想想其一般的步骤是怎样的,先有个步骤之后,不至于在后面的搞混了,这样在整合的时候也比较清晰些. 然后我们就细细的一步一步来整合. 1  创建一个Web项目. 2  导入Mybatis3.Spring4.SpringMVC4.连接数据库(我使用的数据库是mysql)的jar包. 我所用的包:  spring-websocket-4.2.0.RELEASE.jar 3  创建Mybatis3.Spring4.SpringMVC4.连接数据库的配置文件. 4  配置web.x

springmvc整合log4j

1.工程结构 2.所需jar包 3.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" xmlns:web="http://java.sun.com/

玩转Spring MVC(五)----在spring中整合log4j

在前边的基础上,本文主要总结一下如何在spring 中配置log4j,在本文末尾会给出完整项目的链接. 首先是web.xml中要新添加的代码: <!-- 6. 配置log4j --> <!--6.1 配置加载log4j.xml文件路径 --> <context-param> <param-name>log4jConfigLocation</param-name> <param-value>/WEB-INF/classes/spring

SSH整合log4j

Struts,Spring和Hibernate均支持Log4j作为其日志实现系统,因此如果能够合理地配置Log4j,便可以为SSH架构建立起完善的日志系统. SSH框架中使用log4j的好处: 1. 动态的改变记录级别和策略,即修改log4j.properties,不需要重启Web应用,这需要在web.xml中设置一下.2. 把log文件定在/WEB-INF/logs/ 而不需要绝对路径.3. 可以把log4j.properties和其他properties一起放在/WEB-INF/ ,而不是C

【记录】SpringBoot 2.X整合Log4j没有输出INFO、DEBUG等日志信息解决方案

由于批量更新的时候一直无法定位问题出处,就去服务器定位日志,奈何日志一直无法输出,为了能够更好的定位问题,痛定思痛后逐步排查最终解决问题.如有客官看到此处,请不要盲目对号入座,我的项目环境或许与你有区别所以解决方案不一定适合,此贴只作为工作记录,并对出现相同问题,且项目环境相同的朋友作为借鉴而已,如没有帮到,也请嘴下留情. 首先贴出日志文件:log4j2.yml # 共有8个级别,按照从低到高为:ALL < TRACE < DEBUG < INFO < WARN < ERRO

Spring整合log4j

log4j2.xml放在类加载路径下,类加载路径就是WEB-INF文件夹下的classses文件,因为运行时,src包里的java类会被编译成.class盘文件,放在WEB-INF文件夹下的classses文件下,所以既可以放在src包下,也可以放在WEB-INF文件夹下的classses文件下: 暂时只有设置绝对路径储存日志文集那的方法,对应的配置文件如下: <?xml version="1.0" encoding="UTF-8"?> <Conf