在 Logback Spring Rollbar Appender 中按消息过滤事件

Filter event by message in Logback Spring Rollbar Appender

我已经配置好我的 Rollbar Appender in logback-spring.xml:

<appender name="Rollbar" class="com.rollbar.logback.RollbarAppender">
    <accessToken>${ROLLBAR_TOKEN}</accessToken>
    <environment>${SPRING_PROFILES_ACTIVE}</environment>
    <filter class="ch.qos.logback.classic.filter.ThresholdFilter">
        <level>ERROR</level>
    </filter>
</appender>

并为所需的个人资料激活它:

<!-- debug level for dev -->
<springProfile name="dev">
    <root level="debug">
        <appender-ref ref="Console"/>
        <appender-ref ref="Rollbar"/>
    </root>
</springProfile>

一切正常,除了一个问题外,我可以在 Rollbar 中收到错误。有一些我不想在 Rollbar 中看到的错误,但我仍然可以在控制台中看到它们,例如:

io.netty.channel.unix.Errors$NativeIoException: readAddress(..) failed: Connection reset by peer

如何最方便地过滤此类消息?

解决方案是创建您自己的 ch.qos.logback.core.filter.Filter:

实现
public class RegexRollbarFilter extends Filter<ILoggingEvent> {

    private String regex;
    private boolean includeThrowableMessage = true;

    @Override
    public FilterReply decide(ILoggingEvent event) {
        if (!isStarted()) {
            return FilterReply.NEUTRAL;
        }

        IThrowableProxy throwableProxy = event.getThrowableProxy();
        if (event.getMessage()
                 .matches(regex) || includeThrowableMessage && throwableProxy != null && throwableProxy.getMessage()
                                                                                                       .matches(regex)) {
            return FilterReply.DENY;
        } else {
            return FilterReply.NEUTRAL;
        }
    }

    public void setRegex(String regex) {
        this.regex = regex;
    }

    public void setIncludeThrowableMessage(boolean includeThrowableMessage) {
        this.includeThrowableMessage = includeThrowableMessage;
    }

    public void start() {
        if (this.regex != null) {
            super.start();
        }
    }
}

并按以下方式使用它:

 <appender name="Rollbar" class="com.rollbar.logback.RollbarAppender">
        <accessToken>${ROLLBAR_TOKEN}</accessToken>
        <environment>${SPRING_PROFILES_ACTIVE}</environment>
        <filter class="ch.qos.logback.classic.filter.ThresholdFilter">
            <level>ERROR</level>
        </filter>
        <filter class="your.package.RegexRollbarFilter">
            <regex>^.*An existing connection was forcibly closed by the remote host.*$</regex>
        </filter>
        <filter class="your.package.RegexRollbarFilter">
            <regex>(.|\n)*readAddress\(..\) failed: Connection reset by peer(.|\n)*$</regex>
        </filter>
    </appender>