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

Kar*_*ren 3 python logging sentry

每次发生错误/异常时,我一直尝试.log从 python 发送一个“”文件附件到哨兵,但到目前为止没有成功。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");
});
Run Code Online (Sandbox Code Playgroud)

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

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"))
Run Code Online (Sandbox Code Playgroud)

ps 在 python 中,Attachment()对象是在内部创建的scope.add_attachment(),因此不需要显式赋值。我也尝试过push_scope()但是没有太大效果。

对此问题的任何帮助表示赞赏。

Kar*_*ren 5

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

from sentry_sdk import configure_scope
from sentry_sdk.api import capture_exception

configure_scope(lambda scope: scope.add_attachment(path="sentry.log"))
capture_exception(AttributeError())
Run Code Online (Sandbox Code Playgroud)

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