Karen
Karen

Reputation: 431

How to send a logging attachment to Sentry in Python?

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.

Upvotes: 3

Views: 1727

Answers (2)

slamora
slamora

Reputation: 727

From sentry.io Python docs

Sentry can enrich your events for further investigation by storing additional files, such as config or log files, as attachments.

Attachments live on the Scope and will be sent with all events.

Here the sample code about how to add an attachment:

# Add an attachment
from sentry_sdk import configure_scope

with configure_scope() as scope:
    scope.add_attachment(bytes=b"Hello World!", filename="attachment.txt")
    scope.add_attachment(path="/path/to/attachment/file.txt")

More details on Attachments | Sentry for Python

Upvotes: 1

Karen
Karen

Reputation: 431

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

Upvotes: 5

Related Questions