如何在 Python 中向 Sentry 发送日志记录附件?

How to send a logging attachment to Sentry in Python?

每次发生错误/异常时,我一直在尝试从 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"))

p.s。在 python Attachment() 中,对象在 scope.add_attachment() 中创建,因此不需要显式赋值。我也试过push_scope(),但效果不大。

感谢任何有关此问题的帮助。

我可以通过添加这行代码 capture_exception(AttributeError()) 来发送附件,其中 AttributeError() 可以是内置异常或从 Exception class。最小的工作代码如下。

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