How do I not log a particular type of Exception in Logback?

前端 未结 3 1380
礼貌的吻别
礼貌的吻别 2020-12-03 14:51

How do I configure Logback to ignore logging on exceptions of a particular type?

3条回答
  •  忘掉有多难
    2020-12-03 15:21

    You can do it with a simple EvaluatorFilter:

    
        
            java.lang.RuntimeException.class.isInstance(throwable)
        
        DENY
    
    

    Please note that you need the following dependency in your pom.xml as well:

    
        org.codehaus.janino
        janino
        2.5.16
    
    

    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 {
    
        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);
            }
        }
    }
    

    With a proper config:

    
        java.lang.Exception
    
    

    In a TurboFilter you get the thrown Throwable instance directly, so you can call the isInstance method without manually casting the IThrowableProxy to ThrowableProxy.

    Further documentation

提交回复
热议问题