Skip to main content
 首页 » 编程设计

python之在新的 sentry-python SDK 中将 extra 的字典传递给 captureException 有什么等价物

2024年08月14日37linjiqin

为 capture_exception 和 capture_message 传递额外信息到新的 sentry-python SDK 方法的最佳方式是什么?

以前,我会: sentry_id = sentry.captureException(extra=extra)

基于文档和这个 github 问题 ( https://github.com/getsentry/sentry-python/issues/113 ),它就像下面的选项之一是可比较的,但我想不出办法。

使用 capture_exception 接近...

except Exception as e: 
    sentry_id = capture_exception(e, extra=extra) # Error 

...但不允许第二个额外的参数:(

使用 python 日志记录集成 非常接近......

except Exception as e: 
    sentry_id = logging.error(e, exc_info=True, extra=extra) 

...但不返回 Sentry ID :(

同时使用 python 日志记录集成和 capture_exception 接近...

except Exception as e: 
    logging.error(e, exc_info=True, extra=extra) 
    sentry_id = capture_exception(e) 

...但是会在 Sentry 中产生两个单独的错误条目:(

使用 capture_exception with push_scope 很接近...

except Exception as e: 
    with push_scope() as scope: 
        scope.set_extra(extra) # Error 
        sentry_id = capture_exception(e) 

...但不接受字典 :(

是使用最后一种方法的解决方案,它有一个辅助函数,可以将额外的字典解压到许多 scope.set_extra(key, val) 调用中?

感谢您的帮助!

请您参考如下方法:

except Exception as e: 
    with push_scope() as scope: 
        for k, v in extra.items(): 
            scope.set_extra(k, v) 
        sentry_id = capture_exception(e) 

但是,我认为您在错误的时间点设置了 extra。理想情况下,您应该在额外的上下文数据可用并且与当前正在执行的代码相关时立即设置它。推送范围只是为了调用 capture_exception 表示您构建对 set_extra 的调用的方式有问题。

取而代之的是:

logger.error("Event via logging", extra={"foo": 42}) 
 
try: 
    1/0 
except Exception: 
    with push_scope() as scope: 
        scope.set_extra("foo", 42) 
        capture_exception() 

这样做:

with push_scope() as scope: 
    scope.set_extra("foo", 42) 
    logger.error("Event via logging") 
 
    try: 
        1/0 
    except Exception: 
        capture_exception()