我成功地使用Spring的@Scheduled注释每隔几秒钟执行一次方法。唯一的问题是由于这种方法,我从Hibernate和Spring获得了很多有关事务等的日志消息。
我希望保持日志记录级别相同,因为我希望收到此信息以用于应用程序中的其他事务。
在执行特定方法时,是否可以通过logback临时禁止其他库的日志记录?
您需要使用过滤器和MDC(映射的诊断上下文)。此解决方案将仅影响在执行该@Scheduled
方法的线程上发生的日志记录。
@Scheduled
方法中,向该线程的MDC添加一个条目。ch.qos.logback.core.filter.Filter<ILoggingEvent>
,FilterReply.DENY
如果在MDC中设置了该条目,则将返回<appender>
条目中添加对该过滤器的引用logback.xml
使您的@Scheduled
方法如下所示:
@Scheduled(fixedRate=30000)
public void scheduledMethod () {
try{
MDC.put("scheduled", "true");
// Your code here
}finally{
MDC.remove("scheduled");
}
}
我应该提到删除密钥很重要,因为Spring可能会重用线程,而MDC会保留该值。
您的过滤器应如下所示:
package my.domain.application.logging;
import ch.qos.logback.classic.spi.ILoggingEvent;
import ch.qos.logback.core.filter.Filter;
import ch.qos.logback.core.spi.FilterReply;
public class MDCFilter extends Filter<ILoggingEvent> {
@Override
public FilterReply decide(ILoggingEvent event) {
String scheduled = event.getMDCPropertyMap().get("scheduled");
if ("true".equals(scheduled)) {
return FilterReply.DENY;
} else {
return FilterReply.NEUTRAL;
}
}
}
将以下内容添加到您的 logback.xml
<appender name="myAppender" class="ch.qos.logback.core.ConsoleAppender">
<filter class="my.domain.application.logging.MDCFilter" />
<!-- the rest of your appender -->
</appender>
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句