本文介绍了如何不在 Logback 中记录特定类型的异常?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
如何配置 Logback 以忽略特定类型异常的日志记录?
How do I configure Logback to ignore logging on exceptions of a particular type?
推荐答案
你可以用一个简单的EvaluatorFilter
:
<filter class="ch.qos.logback.core.filter.EvaluatorFilter">
<evaluator>
<expression>java.lang.RuntimeException.class.isInstance(throwable)</expression>
</evaluator>
<onMatch>DENY</onMatch>
</filter>
请注意,您的 pom.xml
中还需要以下依赖项:
Please note that you need the following dependency in your pom.xml
as well:
<dependency>
<groupId>org.codehaus.janino</groupId>
<artifactId>janino</artifactId>
<version>2.5.16</version>
</dependency>
另一种可能的解决方案是自定义 Filter
实现:
Another possible solution is a custom Filter
implementation:
import ch.qos.logback.classic.spi.ILoggingEvent;
import ch.qos.logback.classic.spi.IThrowableProxy;
import ch.qos.logback.classic.spi.ThrowableProxy;
import ch.qos.logback.core.filter.Filter;
import ch.qos.logback.core.spi.FilterReply;
public class SampleFilter extends Filter<ILoggingEvent> {
private Class<?> exceptionClass;
public SampleFilter() {
}
@Override
public FilterReply decide(final ILoggingEvent event) {
final IThrowableProxy throwableProxy = event.getThrowableProxy();
if (throwableProxy == null) {
return FilterReply.NEUTRAL;
}
if (!(throwableProxy instanceof ThrowableProxy)) {
return FilterReply.NEUTRAL;
}
final ThrowableProxy throwableProxyImpl =
(ThrowableProxy) throwableProxy;
final Throwable throwable = throwableProxyImpl.getThrowable();
if (exceptionClass.isInstance(throwable)) {
return FilterReply.DENY;
}
return FilterReply.NEUTRAL;
}
public void setExceptionClassName(final String exceptionClassName) {
try {
exceptionClass = Class.forName(exceptionClassName);
} catch (final ClassNotFoundException e) {
throw new IllegalArgumentException("Class is unavailable: "
+ exceptionClassName, e);
}
}
}
使用适当的配置:
<filter class="hu.palacsint.logbacktest.SampleFilter">
<exceptionClassName>java.lang.Exception</exceptionClassName>
</filter>
在 TurboFilter
你直接得到了抛出的Throwable
实例,所以你可以调用isInstance
方法,无需手动将 IThrowableProxy
转换为 ThrowableProxy代码>.
In a TurboFilter
you get the thrown Throwable
instance directly, so you can call the isInstance
method without manually casting the IThrowableProxy
to ThrowableProxy
.
这篇关于如何不在 Logback 中记录特定类型的异常?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!