How to send a logging attachment to Sentry in Python?

Question:

I have been trying to send a ".log" file attachment to sentry from python every time an error/ exception occurs but so far without success. Sentry does not provide attachments documentation for python, so I have been reading the java attachments example (https://docs.sentry.io/platforms/java/enriching-events/attachments/), which is

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");
});

Trying to do a similar conversion in python using sentry_sdk (https://github.com/getsentry/sentry-python/tree/master/sentry_sdk), my code is:

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. In python Attachment() objects gets created inside scope.add_attachment(), so no need for explicit assignment. I also tried push_scope() but did not have much effect.

Any help on this issue is appreciated.

Asked By: Karen

||

Answers:

I was able to send an attachment by adding this line of code capture_exception(AttributeError()) where AttributeError() can be a built-in exception or a custom one derived from the Exception class. A minimal working code is the following.

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())

You may further explore by visiting
https://github.com/getsentry/sentry-python/blob/master/tests/test_basics.py

Answered By: Karen
Categories: questions Tags: , ,
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.