【问题标题】:How to ignore certain Python errors from Sentry capture如何从 Sentry 捕获中忽略某些 Python 错误
【发布时间】:2020-01-09 17:27:45
【问题描述】:

我已将 Sentry 配置为从 Django+Celery 应用程序中捕获所有错误。它工作正常,但我发现一个令人讨厌的用例是当我必须重新启动我的 Celery 工作程序、PostgreSQL 数据库或消息传递服务器时,这会导致数以千计的各种“无法访问数据库/消息传递服务器”错误。这会污染 Sentry 报告,有时甚至超出我的活动配额。

Their docs 提到了一个“ignore_exceptions”参数,但它在他们旧的已弃用的客户端中,我没有使用,也不建议将其用于新项目。您将如何在新 API 中执行此操作?

【问题讨论】:

    标签: python django celery sentry


    【解决方案1】:

    您可以使用before-send 按任意标准过滤错误。由于不清楚您实际想要过滤什么,这里有一个按类型过滤的示例。但是,您可以使用自定义逻辑将其扩展为例如按异常消息匹配。

    import sentry_sdk
    
    def before_send(event, hint):
        if 'exc_info' in hint:
            exc_type, exc_value, tb = hint['exc_info']
            if isinstance(exc_value, (IgnoredErrorFoo, IgnoredErrorBar)):
                return None
        return event
    
    sentry_sdk.init(before_send=before_send)
    

    【讨论】:

      【解决方案2】:

      我花了一些时间才真正找到它,但新 SDK 中的选项是“ignore_errors”。它需要一个迭代,其中每个元素可以是字符串或类型(如旧接口)。

      我犹豫是否要链接到它,因为它是一种随时可能更改的内部方法,但 here 是我写这篇文章时的快照。

      作为一个例子(重新实现马库斯的答案):

      import sentry_sdk
      
      sentry_dsk.init(ignore_errors=(IgnoredErrorFoo, IgnoredErrorBar))
      

      【讨论】:

      • 这是给他们的老客户(“raven”)还是给他们的新客户?我非常讨厌这种分裂。
      • @mlissner 新的(链接的 blob 的编辑日期为 4 月 17 日)
      【解决方案3】:

      要忽略所有相关错误,有两种方法:

      1. 使用 before_send
      import sentry_sdk
      from rest_framework.exceptions import ValidationError
      
      def before_send(event, hint):
          if 'exc_info' in hint:
              exc_type, exc_value, tb = hint['exc_info'] 
              if isinstance(exc_value, (KeyError, ValidationError)):
                  return None
          return event
      
      sentry_sdk.init(
          dsn='SENTRY_DSN',
          before_send=before_send
      )
      
      1. 使用ignore_errors
      import sentry_sdk
      from rest_framework.exceptions import ValidationError
      
      sentry_dsk.init(
          dsn='SENTRY_DSN',
          ignore_errors=[
             KeyError() ,
             ValidationError('my error message'),
          ]  # All event error (KeyError, ValidationError) will be ignored
      )
      

      要忽略特定事件错误,只需使用自定义def before_send 忽略此事件ValidationError('my error message'):

      def before_send(event, hint):
          if 'exc_info' in hint:
              exc_type, exc_value, tb = hint['exc_info'] 
              if exc_value.args[0] in ['my error message', 'my error message 2', ...]:
                  return None
          return event
      

      这记录在 sentry-python 文档中:https://sentry-python.readthedocs.io/en/latest/api.html

      【讨论】:

      • 你在 if exc_value.args[0] in ['my error message', 'my error message 2', ...])的末尾多了一个括号:
      猜你喜欢
      • 2014-09-07
      • 1970-01-01
      • 2012-03-02
      • 1970-01-01
      • 2019-03-26
      • 1970-01-01
      • 2020-12-09
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多