Skip to content

Commit

Permalink
Respect repr on fields when logging a dataclass (#592)
Browse files Browse the repository at this point in the history
  • Loading branch information
dmontagu authored Nov 14, 2024
1 parent dd6c380 commit a316c91
Show file tree
Hide file tree
Showing 3 changed files with 18 additions and 3 deletions.
2 changes: 1 addition & 1 deletion logfire/_internal/json_encoder.py
Original file line number Diff line number Diff line change
Expand Up @@ -250,7 +250,7 @@ def to_json_value(o: Any, seen: set[int]) -> JsonValue:
elif is_sqlalchemy(o):
return _get_sqlalchemy_data(o, seen)
elif dataclasses.is_dataclass(o):
return {f.name: to_json_value(getattr(o, f.name), seen) for f in dataclasses.fields(o)}
return {f.name: to_json_value(getattr(o, f.name), seen) for f in dataclasses.fields(o) if f.repr}
elif is_attrs(o):
return _get_attrs_data(o, seen)

Expand Down
4 changes: 3 additions & 1 deletion logfire/_internal/json_schema.py
Original file line number Diff line number Diff line change
Expand Up @@ -171,7 +171,9 @@ def attributes_json_schema_properties(attributes: dict[str, Any]) -> JsonSchemaP
def _dataclass_schema(obj: Any, seen: set[int]) -> JsonDict:
# NOTE: The `x-python-datatype` is "dataclass" for both standard dataclasses and Pydantic dataclasses.
# We don't need to distinguish between them on the frontend, or to reconstruct the type on the JSON formatter.
return _custom_object_schema(obj, 'dataclass', (field.name for field in dataclasses.fields(obj)), seen)
return _custom_object_schema(
obj, 'dataclass', (field.name for field in dataclasses.fields(obj) if field.repr), seen
)


def _bytes_schema(obj: bytes, _seen: set[int]) -> JsonDict:
Expand Down
15 changes: 14 additions & 1 deletion tests/test_json_args.py
Original file line number Diff line number Diff line change
Expand Up @@ -5,7 +5,7 @@
import sys
from collections import deque
from collections.abc import Sequence
from dataclasses import dataclass
from dataclasses import dataclass, field
from datetime import date, datetime, time, timedelta
from decimal import Decimal
from enum import Enum
Expand Down Expand Up @@ -71,6 +71,12 @@ class MyPydanticComplexDataclass:
t: MyPydanticDataclass


@dataclass
class MyReprDataclass:
in_repr: int
not_in_repr: MyDataclass = field(repr=False)


class MySQLModel(SQLModel):
s: int

Expand Down Expand Up @@ -577,6 +583,13 @@ class StrSubclass(str):
},
id='pydantic_complex_dataclass',
),
pytest.param(
MyReprDataclass(in_repr=1, not_in_repr=MyDataclass(t=2)),
'MyReprDataclass(in_repr=1)',
'{"in_repr":1}',
{'type': 'object', 'title': 'MyReprDataclass', 'x-python-datatype': 'dataclass'},
id='repr_dataclass',
),
pytest.param(
ValueError('Test value error'),
'Test value error',
Expand Down

0 comments on commit a316c91

Please sign in to comment.