【问题标题】:How to send a logging attachment to Sentry in Python?如何在 Python 中向 Sentry 发送日志记录附件?
【发布时间】:2021-12-03 11:31:48
【问题描述】:

每次发生错误/异常时,我一直在尝试从 python 向哨兵发送“.log”文件附件,但到目前为止没有成功。 Sentry没有提供python的附件文档,所以我一直在阅读java附件示例(https://docs.sentry.io/platforms/java/enriching-events/attachments/),即

import io.sentry.Sentry;
import io.sentry.Attachment;

Attachment fileAttachment = new Attachment("your/path/file.log");

// Global Scope
Sentry.configureScope(scope -> {
  scope.addAttachment(fileAttachment);
});

// Clear all attachments in the global Scope
Sentry.configureScope(scope -> {
  scope.clearAttachments();
});

// Local Scope
Sentry.withScope(scope -> {
  scope.addAttachment(fileAttachment);
  Sentry.captureMessage("my message");
});

尝试在 python 中使用 sentry_sdk (https://github.com/getsentry/sentry-python/tree/master/sentry_sdk) 进行类似的转换,我的代码是:

from sentry_sdk.scope import Scope
from sentry_sdk import configure_scope, push_scope

scope=Scope()
configure_scope(lambda scope: scope.add_attachment(path="sentry.log"))
push_scope(lambda scope: scope.add_attachment(path="sentry.log"))

附言在 python 中,Attachment() 对象是在scope.add_attachment() 中创建的,因此不需要显式分配。我也试过push_scope(),但效果不大。

感谢您对此问题的任何帮助。

【问题讨论】:

    标签: python logging sentry


    【解决方案1】:

    我可以通过添加这行代码capture_exception(AttributeError()) 来发送附件,其中AttributeError() 可以是内置异常,也可以是从Exception 类派生的自定义异常。一个最小的工作代码如下。

    from sentry_sdk.scope import Scope
    from sentry_sdk import configure_scope, push_scope
    from sentry_sdk.api import capture_exception
    
    configure_scope(lambda scope: scope.add_attachment(path="sentry.log"))
    capture_exception(AttributeError())
    

    您可以通过访问进一步探索 https://github.com/getsentry/sentry-python/blob/master/tests/test_basics.py

    【讨论】:

      猜你喜欢
      • 2019-10-11
      • 2018-12-20
      • 1970-01-01
      • 2021-09-02
      • 1970-01-01
      • 2019-05-23
      • 1970-01-01
      • 2021-08-15
      • 1970-01-01
      相关资源
      最近更新 更多