Skip to content

fix(serializer): Implement abstract base class for customizing serialization #1363

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Closed
wants to merge 3 commits into from
Closed
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
14 changes: 11 additions & 3 deletions sentry_sdk/serializer.py
Original file line number Diff line number Diff line change
Expand Up @@ -2,6 +2,7 @@
import math

from datetime import datetime
from abc import ABC, abstractmethod

from sentry_sdk.utils import (
AnnotatedValue,
Expand Down Expand Up @@ -70,7 +71,7 @@

MAX_DATABAG_DEPTH = 5
MAX_DATABAG_BREADTH = 10
CYCLE_MARKER = u"<cyclic>"
CYCLE_MARKER = "<cyclic>"


global_repr_processors = [] # type: List[ReprProcessor]
Expand All @@ -81,6 +82,13 @@ def add_global_repr_processor(processor):
global_repr_processors.append(processor)


class SentryReprMixin(ABC):
@abstractmethod
def sentry_repr(self):
# type: () -> str
pass


class Memo(object):
__slots__ = ("_ids", "_objs")

Expand Down Expand Up @@ -228,7 +236,7 @@ def _serialize_node(
capture_internal_exception(sys.exc_info())

if is_databag:
return u"<failed to serialize, use init(debug=True) to see error logs>"
return "<failed to serialize, use init(debug=True) to see error logs>"

return None
finally:
Expand Down Expand Up @@ -281,7 +289,7 @@ def _serialize_node_impl(
else:
return obj

elif callable(getattr(obj, "sentry_repr", None)):
elif isinstance(obj, SentryReprMixin):
return obj.sentry_repr()

elif isinstance(obj, datetime):
Expand Down
6 changes: 3 additions & 3 deletions tests/test_serializer.py
Original file line number Diff line number Diff line change
Expand Up @@ -2,7 +2,7 @@

import pytest

from sentry_sdk.serializer import serialize
from sentry_sdk.serializer import serialize, SentryReprMixin

try:
from hypothesis import given
Expand Down Expand Up @@ -51,7 +51,7 @@ def inner(message, **kwargs):
def test_bytes_serialization_decode(message_normalizer):
binary = b"abc123\x80\xf0\x9f\x8d\x95"
result = message_normalizer(binary, should_repr_strings=False)
assert result == u"abc123\ufffd\U0001f355"
assert result == "abc123\ufffd\U0001f355"


@pytest.mark.xfail(sys.version_info < (3,), reason="Known safe_repr bugs in Py2.7")
Expand All @@ -67,7 +67,7 @@ def test_serialize_sets(extra_normalizer):


def test_serialize_custom_mapping(extra_normalizer):
class CustomReprDict(dict):
class CustomReprDict(dict, SentryReprMixin):
def sentry_repr(self):
return "custom!"

Expand Down