Spring与Logback整合

 最近项目中使用了logback作为日志处理,可是对这个不是很熟悉,所以就写些博客记录下学习的过程。本篇博客是这系列的第一篇。 

 因为我在logback中需要使用到发送Email,为了便于在本地Eclipse中方便测试,你需要安装一个Eclipse Email plugin,具体参考mailsnag。

logback的官方网站http://logback.qos.ch/manual/configuration.html 。

1.  在web.xml文件中配置spring与logback整合需要的listener.


        logbackConfigLocation
        classpath:log/logback.xml
    

    
        com.npf.listener.SpringMVCLogbackConfigListener
    

2. 这里我们使用了自己的SpringMVCLogbackConfigListener, 而这个listener实际上继承了ch.qos.logback.ext.spring.web.LogbackConfigListener.

package com.npf.listener;

import javax.servlet.ServletContextEvent;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.slf4j.impl.StaticLoggerBinder;

import ch.qos.logback.classic.LoggerContext;
import ch.qos.logback.ext.spring.web.LogbackConfigListener;


public class SpringMVCLogbackConfigListener extends LogbackConfigListener{
	
	private final static Logger LOGGER = LoggerFactory.getLogger(SpringMVCLogbackConfigListener.class);
	
	@Override
	public void contextInitialized(ServletContextEvent paramServletContextEvent) {
		super.contextInitialized(paramServletContextEvent);
		LoggerContext localLoggerContext = (LoggerContext)StaticLoggerBinder.getSingleton().getLoggerFactory();
		String smtpHost = localLoggerContext.getProperty("smtpHost");
		LOGGER.info("this smtpHost is {}",smtpHost);
	}

}

3. 配置logback.xml, 这里有一个小坑。在logback.xml有这么一个配置:

我当初scope="context"没有写,就总是会发现Spring不能把properties属性注入到logback中,非常郁闷。后来查阅了官方文档才知道:

A property can be defined for insertion in local scope, in context scope, or in system scope. Local scope is the default. Although it is possible to read variables from the OS environment, it is not possible to write into the OS environment.

LOCAL SCOPE A property with local scope exists from the point of its definition in a configuration file until the end of interpretation/execution of said configuration file. As a corollary, each time a configuration file is parsed and executed, variables in local scope are defined anew.

CONTEXT SCOPE A property with context scope is inserted into the context and lasts as long as the context or until it is cleared. Once defined, a property in context scope is part of the context. As such, it is available in all logging events, including those sent to remote hosts via serialization.

SYSTEM SCOPE A property with system scope is inserted into the JVM's system properties and lasts as long as the JVM or until it is cleared.

Properties are looked up in the the local scope first, in the context scope second, in the system properties scope third, and in the OS environment last.
During substitution, properties are looked up in the local scope first, in the context scope second, in the system properties scope third, and in the OS environment fourth and last.

The scope attribute of the element, element or the element can be used to set the scope of a property. The scope attribute admits "local", "context" and "system" strings as possible values. If not specified, the scope is always assumed to be "local".

原文请参考:http://logback.qos.ch/manual/configuration.html

那么我的具体配置如下:





	

	
		
			%date %-5level [%thread] %logger - %m%n
		
	
	
	
		${log.dir}/WebApi.log
		
			${log.dir}/WebApi-%d{yyyy-MM-dd}.%i.log
			
			
				1MB
			
		
		
			%date %-5level [%thread] %logger - %m%n
		
	
	
	
		${log.dir}/access.log
		
			${log.dir}/access-%d{yyyy-MM-dd}.log
			30
		
		
			%date - %m%n
		
		false 
	
	
	
		
	      error
	      ACCEPT
	      DENY
	    
		${smtpHost}
		${smtpPort}  
		${to}
		${from}
		logback Test
		
			%date%level%thread%logger%message
		
	

	
		
		
		
	
	
	
		
	


4.我的controller如下,因为我需要测试邮件,所以将logger设置为了error.

package com.npf.controller;

import java.util.Map;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;

import com.npf.service.StudentService;

@Controller
public class HomeController {
	
	private final static Logger LOGGER = LoggerFactory.getLogger(HomeController.class);
	
	@Autowired
	@Qualifier("studentServiceImpl")
	private StudentService studentService;
	
	@RequestMapping(value={"/","/home"})
	public String showHomePage(Map map){
		map.put("stuList", studentService.getStudents());
		LOGGER.error("this student list is {}", studentService.getStudents());
		return "home";
	}
}

5. 启动服务,访问页面并且将Email Messages 插件启动:

5.1 主页如下:

Spring与Logback整合_第1张图片

5.2 我们收到了邮件。

双击可以打开这个邮件。

Spring与Logback整合_第2张图片

5.3 我们可以找到本地磁盘的log文件,并打开查看。

Spring与Logback整合_第3张图片

6. 这个博客用到的源代码已托管到GitHub, 如果你感兴趣,可以查看Spring与Logback整合

你可能感兴趣的:([专栏]Logback日志框架)