继上一篇文章中所集成的是基于Java的普通项目,如果要在Spring和Spring MVC上集成,需要做如下处理:

一、Spring

POM:



<!-- Logback -->
<!-- https://mvnrepository.com/artifact/ch.qos.logback/logback-classic -->
<dependency>
<groupId>ch.qos.logback</groupId>
<artifactId>logback-classic</artifactId>
<version>1.2.3</version>
</dependency>
<!-- https://mvnrepository.com/artifact/ch.qos.logback/logback-core -->
<dependency>
<groupId>ch.qos.logback</groupId>
<artifactId>logback-core</artifactId>
<version>1.2.3</version>
</dependency>
<!-- https://mvnrepository.com/artifact/org.logback-extensions/logback-ext-spring -->
<dependency>
<groupId>org.logback-extensions</groupId>
<artifactId>logback-ext-spring</artifactId>
<version>0.1.4</version>
</dependency>
<!-- https://mvnrepository.com/artifact/org.slf4j/slf4j-api -->
<dependency>
<groupId>org.slf4j</groupId>
<artifactId>slf4j-api</artifactId>
<version>1.7.25</version>
</dependency>
<!-- https://mvnrepository.com/artifact/org.slf4j/jcl-over-slf4j -->
<dependency>
<groupId>org.slf4j</groupId>
<artifactId>jcl-over-slf4j</artifactId>
<version>1.7.25</version>
</dependency>


其中logback-ext-spring这个JAR包是为了和Spring一起使用。jcl-over-slf4j:commons-logging到slf4j的桥梁

此时不需要设置logback.xml也可以输出日志。

示例工程:​​https://github.com/easonjim/5_java_example/tree/master/springtest/test22/HelloSpring​

二、Spring MVC

POM和上面一样,关键的点在于配置web.xml中的Listen,并且指定一个logback.xml文件

logback.xml:



<?xml version="1.0" encoding="UTF-8"?>
<configuration>
<!-- 控制台输出 -->
<appender name="STDOUT" class="ch.qos.logback.core.ConsoleAppender">
<!-- 日志输出编码 -->
<Encoding>UTF-8</Encoding>
<layout class="ch.qos.logback.classic.PatternLayout">
<!--格式化输出:%d表示日期,%thread表示线程名,%-5level:级别从左显示5个字符宽度%msg:日志消息,%n是换行符-->
<pattern>%d{yyyy-MM-dd HH:mm:ss.SSS} [%thread] %-5level %logger{50} - %msg%n
</pattern>
</layout>
</appender>
<!-- 日志输出级别 -->
<root level="INFO">
<appender-ref ref="STDOUT" />
</root>
</configuration>


web.xml:



<?xml version="1.0" encoding="UTF-8"?>
<!-- 配置XML模式 -->
<web-app id="WebApp_ID" version="3.1"
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_3_1.xsd">

<display-name>Archetype Created Web Application</display-name>

<!-- 配置Servlet,Spring接管 -->
<servlet>
<servlet-name>SrpingMVCTest</servlet-name>
<servlet-class>
org.springframework.web.servlet.DispatcherServlet
</servlet-class>
<load-on-startup>1</load-on-startup>
</servlet>

<!-- 配置Servlet,Spring接管 -->
<servlet-mapping>
<servlet-name>SrpingMVCTest</servlet-name>
<url-pattern>/</url-pattern>
</servlet-mapping>

<!-- 添加日志监听器 -->
<context-param>
<param-name>logbackConfigLocation</param-name>
<param-value>classpath:logback.xml</param-value>
</context-param>
<listener>
<listener-class>ch.qos.logback.ext.spring.web.LogbackConfigListener</listener-class>
</listener>

</web-app>


配置完之后就可以输出日志。

实例工程:​​https://github.com/easonjim/5_java_example/tree/master/springmvc/tutorialspoint/test34/test1​