如何在 Logback 中不记录特定类型的异常?

发布于 2024-11-10 06:15:58 字数 35 浏览 2 评论 0 原文

如何配置 Logback 以忽略特定类型异常的日志记录?

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

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(3

全部不再 2024-11-17 06:15:58

您可以使用简单的 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 中添加以下依赖项:

<dependency>
    <groupId>org.codehaus.janino</groupId>
    <artifactId>janino</artifactId>
    <version>3.1.9</version>
</dependency>

另一种可能的解决方案是自定义 Filter< /code> 实现:

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 方法,无需手动转换IThrowableProxyThrowableProxy

更多文档

You can do it with a simple EvaluatorFilter:

<filter class="ch.qos.logback.core.filter.EvaluatorFilter">
    <evaluator>
        <expression>java.lang.RuntimeException.class.isInstance(throwable)</expression>
    </evaluator>
    <onMatch>DENY</onMatch>
</filter>

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

<dependency>
    <groupId>org.codehaus.janino</groupId>
    <artifactId>janino</artifactId>
    <version>3.1.9</version>
</dependency>

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

With a proper config:

<filter class="hu.palacsint.logbacktest.SampleFilter">
    <exceptionClassName>java.lang.Exception</exceptionClassName>
</filter>

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

二智少女猫性小仙女 2024-11-17 06:15:58

这个问题已有 5 年历史了,但我提供我找到的解决方案只是为了使其保持最新状态。

我在官方文档中找到了解决方案:
http://logback.qos.ch/manual/layouts.html

对于我的特殊情况,这是一个运行普通旧 servlet(啊,那些日子)的 17 年老网站,如果用户未登录,servlet 现在会抛出异常。所以这是我的代码片段:

Servlet

  try {
    InvalidLoginException.throwIfBadLogin(webUser);

    // main logic here

  } catch (InvalidLoginException e) {
    throw e;
  } catch (Throwable t) {
    log.error(t);
    throw new UnhandledException(t);
  }

web.xml

<error-page>
    <exception-type>com.mycompany.servlet.exception.InvalidLoginException</exception-type>
    <location>/servlet/Login</location>
</error-page>

从上面的设置来看,我不想记录此异常,因为它并不是真正的异常,而是重定向到登录的逻辑中断。

因此,我的 logback.xml 文件的开头是这样的:

  <configuration packagingData="true" scan="true" debug="true" scanPeriod="30 seconds">
    <evaluator name="InvalidLoginExceptionSuppressor">
      <expression>throwable != null && throwable instanceof com.mycompany.servlet.exception.InvalidLoginException</expression>
    </evaluator>

在 logback.xml 文件中,我的附加程序如下:

  <appender name="STDOUT" class="ch.qos.logback.core.ConsoleAppender">
    <encoder>
      <pattern>%d{MM-dd HH:mm:ss.SSS} %-5level %logger{36} - %msg %ex{full,InvalidLoginExceptionSuppressor}%n</pattern>
      <immediateFlush>false</immediateFlush>
    </encoder>

另请注意,为了完成这项工作,我必须包含 janino 来处理表达式解析。

This question is 5 years old, but I'm supplying the solution I found just to keep it up to date.

I found a solution in the offical docs:
http://logback.qos.ch/manual/layouts.html

For my particular situation, which is a 17 year old web site running plain old servlets (ah, the days), the servlet is now throwing an exception if the user was not logged in. So here's my code snippets:

Servlet

  try {
    InvalidLoginException.throwIfBadLogin(webUser);

    // main logic here

  } catch (InvalidLoginException e) {
    throw e;
  } catch (Throwable t) {
    log.error(t);
    throw new UnhandledException(t);
  }

web.xml

<error-page>
    <exception-type>com.mycompany.servlet.exception.InvalidLoginException</exception-type>
    <location>/servlet/Login</location>
</error-page>

From the setup above, I didn't want to log this exception as it's not really an exception, but rather a break in logic to redirect to login.

So, the start of my logback.xml file is this:

  <configuration packagingData="true" scan="true" debug="true" scanPeriod="30 seconds">
    <evaluator name="InvalidLoginExceptionSuppressor">
      <expression>throwable != null && throwable instanceof com.mycompany.servlet.exception.InvalidLoginException</expression>
    </evaluator>

and further down in the logback.xml file, my appenders:

  <appender name="STDOUT" class="ch.qos.logback.core.ConsoleAppender">
    <encoder>
      <pattern>%d{MM-dd HH:mm:ss.SSS} %-5level %logger{36} - %msg %ex{full,InvalidLoginExceptionSuppressor}%n</pattern>
      <immediateFlush>false</immediateFlush>
    </encoder>

Also note, in order to this work, I had to include janino to handle the expression parsing.

泪意 2024-11-17 06:15:58

这是 @palacsint 响应的另一个示例,当错误不是使用 JaninoEventEvaluator

<filter class="ch.qos.logback.core.filter.EvaluatorFilter">
  <evaluator>
    <expression>logger.equals("org.docx4j.fonts.GlyphCheck") && level == ERROR</expression>
  </evaluator>
  <onMatch>DENY</onMatch>
</filter>

This is an additional example of the response of @palacsint that apply when the error is not an exception using JaninoEventEvaluator:

<filter class="ch.qos.logback.core.filter.EvaluatorFilter">
  <evaluator>
    <expression>logger.equals("org.docx4j.fonts.GlyphCheck") && level == ERROR</expression>
  </evaluator>
  <onMatch>DENY</onMatch>
</filter>
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文