【问题标题】:How to catch python warnings with sentry?如何用哨兵捕捉python警告?
【发布时间】:2021-12-05 08:20:21
【问题描述】:

通过sentry_sdk,哨兵文档解释了如何自动捕获异常或记录消息。但是,我怎样才能捕捉到 python 警告,比如 DeprecationWarning 会引发

warnings.warn(DeprecationWarning, "warning message")

【问题讨论】:

    标签: python warnings sentry


    【解决方案1】:

    在哨兵中没有特定的 API 用于发送警告,但是,您需要确保使用您正在使用的通用日志基础架构记录这些。

    例如,如果您使用的是 Django,则必须在 settings.py 文件中将日志记录级别更改为如下所示的警告

    LOGGING = {
        'version': 1,
        'disable_existing_loggers': False,
        'formatters': {
            'verbose': {
                'format': '%(asctime)s %(levelname)s [%(name)s:%(lineno)s] %(module)s %(process)d %(thread)d %(message)s'
            }
        },
        'handlers': {
            'console': {
                'level': 'WARNING',
                'class': 'logging.StreamHandler'
            },
        },
        'loggers': {
            "": {
                "level": "WARNING",
                'handlers': ['console'],
                "propagate": True
            }
        }
    }
    

    并且哨兵配置没有变化

    import sentry_sdk
    from sentry_sdk.integrations.django import DjangoIntegration
    
    sentry_config = {
        'dsn': os.getenv("SENTRY_DSN", "YOUR CDN"),
        'integrations': [DjangoIntegration()],
        # Set traces_sample_rate to 1.0 to capture 100%
        # of transactions for performance monitoring.
        # We recommend adjusting this value in production.
        'traces_sample_rate': 1.0,
        # If you wish to associate users to errors (assuming you are using
        # django.contrib.auth) you may enable sending PII data.
        'send_default_pii': True
    }
    sentry_sdk.init(**sentry_config)
    

    如果您没有 Logging 基础架构,您可以实现自己的, 检查这个Question,它有很多关于如何创建自定义记录器的示例。

    只需将您的级别更改为 WARNING 并创建一个控制台处理程序(StreamHandler),然后 Sentry 将负责其余的工作

    编辑:我的意思是捕获logging.warning(),但是对于warnings.warn(),您必须记录它们,Python 提供了logging 模块和warnings 模块之间的内置集成让你这样做;只需在脚本或自定义记录器的开头调用logging.captureWarnings(True),警告模块发出的所有警告都会自动记录在警告级别。

    【讨论】:

    • edit 部分回答了问题。
    【解决方案2】:

    在 Python 中,您可以通过不传递参数来捕获捕获的异常或当前保存在 sys.exc_info() 中的异常:

    from sentry_sdk import capture_exception
    
    try:
        a_potentially_failing_function()
    except Exception as e:
        # Alternatively the argument can be omitted
        capture_exception(e)
    

    另一个常见的操作是捕获裸消息。消息是应该发送给 Sentry 的文本信息。通常不会发出消息,但它们可能对某些团队有用。

    from sentry_sdk import capture_message
    
    capture_message('Something went wrong')
    

    【讨论】:

      【解决方案3】:

      如果异常:

      try:
          ...
      except Exception as exc:
          sentry_sdk.capture_exception(exc)
      

      如果消息:

      sentry_sdk.capture_message("xxx")
      

      【讨论】:

      • 谢谢,但这与问题无关。最初的问题是关于警告,而不是关于异常或消息。
      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2011-01-25
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2021-05-07
      • 1970-01-01
      相关资源
      最近更新 更多