logback系列之四:输出日志到不同文件

阅读更多
logback系列之一:输出日志到控制台
logback系列之二:输出日志到文件
logback系列之三:输出日志到文件(滚动)
logback系列之四:输出日志到不同文件


为了方便查看和归档:
不同包的日志可能要放到不同的文件中,如service层和dao层的日志;
不同日志级别:调试、信息、警告和错误等也要分文件输出。

一、根据包输出,通过logger的name属性指定不同的包

1. 创建不同包下的两个类:
package com.john.service;

@Service
public class ObligationService {
	static final Logger log = LoggerFactory.getLogger(ObligationService.class);

	@Resource
	ObligationDao dao;
	
	public void obligate() {
		log.debug("obligate start...");
		dao.queryObligations();
		log.error("An error occurred during the progress");
		log.debug("obligate end...");
	}
}


package com.john.dao;

@Repository
public class ObligationDao {
	static final Logger log = LoggerFactory.getLogger(ObligationDao.class);
	
	public void queryObligations() {
		log.debug("query obligations start...");
		log.error("An error occurred during the query");
		log.debug("query obligations end...");
	}
}


2. 在logback(-test).xml中添加:

    /logs/bribery.log
    
        /logs/bribery-%d{yyyy-MM-dd}.log
    
    
        %d{HH:mm:ss.SSS} [%thread] %-5level %logger{5} - %msg%n
    



    /logs/venality.log
    
        /logs/venality-%d{yyyy-MM-dd}.log
    
    
        %d{HH:mm:ss.SSS} [%thread] %-5level %logger{5} - %msg%n
    



    



    



在类路径下创建Spring的beans.xml文件:(beans节点省略)



3. 测试方法:
	@Test
	public void dispatchByPackageTest() {
		AbstractApplicationContext ctx = new ClassPathXmlApplicationContext("beans.xml");
		ObligationService service = ctx.getBean(ObligationService.class);
		service.obligate();
	}

执行测试后,
bribery.log:
15:59:59.839 [main] DEBUG c.j.s.ObligationService - obligate start...
15:59:59.844 [main] ERROR c.j.s.ObligationService - An error occurred during the progress
15:59:59.844 [main] DEBUG c.j.s.ObligationService - obligate end...

venality.log:
15:59:59.844 [main] DEBUG c.j.d.ObligationDao - query obligations start...
15:59:59.844 [main] ERROR c.j.d.ObligationDao - An error occurred during the query
15:59:59.844 [main] DEBUG c.j.d.ObligationDao - query obligations end...

二、根据日志级别输出

这里把所有级别为ERROR的日志输出到一个文件中

1. 修改logback(-test).xml文件

serviceAppender和daoAppender都加入以下 级别过滤器,这样错误日志就不会在bribery.log和venality.log中打印了:

	ERROR
	DENY
	ACCEPT



新建一个错误日志的appender:

    /logs/error.log
    
        /logs/venality-%d{yyyy-MM-dd}.log
    
    
        %d{HH:mm:ss.SSS} %thread %X{invokeNo} %logger{40} %msg%n
    
    
        ERROR
        ACCEPT
        DENY
    



name为com.john.dao和com.john.service的logger都加上errorAppender:



2. 执行上面的测试方法,service和dao的错误日志都打印到error.log文件中了:
16:12:51,433 main com.john.dao.ObligationDao An error occurred during the query
16:12:51,433 main com.john.service.ObligationService An error occurred during the progress

你可能感兴趣的:(java,logback,xml)