SpringMVC系列之三:集成Log4j

SpringMVC系列之一、集成JSP

SpringMVC系列之二、集成FreeMarker

SpringMVC系列之三、集成Log4j

在SpringMVC系列之二、集成FreeMarker基础上,

1.往pom.xml文件添加log4j依赖:

<properties>
    <slf4j.api.version>1.7.5</slf4j.api.version>
  </properties>

  <dependencies>
    <dependency>
      <groupId>org.slf4j</groupId>  
      <artifactId>slf4j-log4j12</artifactId>  
      <version>${slf4j.api.version}</version>  
    </dependency>
  </dependencies>

2.在web.xml添加:

<context-param>
    <param-name>log4jConfigLocation</param-name>
    <param-value>classpath:log4j.properties</param-value><!-- log4j配置文件路径 -->
  </context-param>

  <listener>
  	<!-- 容器初始化(销毁)时开启(关闭)Log4j -->
  	<listener-class>org.springframework.web.util.Log4jConfigListener</listener-class>
  </listener>

3.在工程类路径下创建log4j.properties文件:

log4j.rootLogger=debug, stdout

log4j.appender.stdout=org.apache.log4j.ConsoleAppender
log4j.appender.stdout.layout=org.apache.log4j.PatternLayout

# Pattern to output the caller's file name and line number.
log4j.appender.stdout.layout.ConversionPattern=%-5p [%t] (%F:%L) -%m%n

4.创建LoggingController控制器:

@Controller
@RequestMapping("/permutation")
public class LoggingController {
	
	static final org.slf4j.Logger log = org.slf4j.LoggerFactory.getLogger(LoggingController.class); // 通用日志API,较流行
	//static final org.apache.log4j.Logger log = org.apache.log4j.Logger.getLogger(LoggingController.class); // 依赖log4j的API,有侵入性,不能使用其它实现
	//static final java.util.logging.Logger log = java.util.logging.Logger.getLogger("LoggingController"); // Java日志API,较古老
	
	@RequestMapping("/index")
	public String indexPage() {
		log.info("Requesting /index");
		return "main.ftl";
	}
}

在mvc-ftl.xml加入:

<!-- 可选,如果未配置,SpringMVC将使用默认配置文件DispatcherServlet.properties的DefaultAnnotationHandlerMapping和AnnotationMethodHandlerAdapter -->
<mvc:annotation-driven /><!-- 注册RequestMappingHandlerMapping, RequestMappingHandlerAdapter和ExceptionHandlerExceptionResolver以提供对@RequestMapping,@ExceptionHandler等注解的支持 -->

<context:component-scan base-package="com.john.logging.controller">
    <context:include-filter type="annotation" expression="org.springframework.stereotype.Controller"/>
</context:component-scan>

在/WEB-INF/ftl下新建main.ftl文件

5.调试工程,查看控制台输出。

相关推荐