Skip to content

Commit 747f0f3

Browse files
feat(logs): Add user attributes to logs
Closes #4422
1 parent 385c668 commit 747f0f3

File tree

2 files changed

+57
-0
lines changed

2 files changed

+57
-0
lines changed

sentry_sdk/client.py

Lines changed: 14 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -927,6 +927,20 @@ def _capture_experimental_log(self, current_scope, log):
927927
elif propagation_context is not None:
928928
log["trace_id"] = propagation_context.trace_id
929929

930+
if self.should_send_default_pii() and isolation_scope._user is not None:
931+
for log_attribute, user_attribute in (
932+
("user.id", "id"),
933+
("user.name", "username"),
934+
("user.email", "email"),
935+
):
936+
if (
937+
user_attribute in isolation_scope._user
938+
and log_attribute not in log["attributes"]
939+
):
940+
log["attributes"][log_attribute] = isolation_scope._user[
941+
user_attribute
942+
]
943+
930944
# If debug is enabled, log the log to the console
931945
debug = self.options.get("debug", False)
932946
if debug:

tests/test_logs.py

Lines changed: 43 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -484,6 +484,49 @@ def test_auto_flush_logs_after_100(sentry_init, capture_envelopes):
484484
raise AssertionError("200 logs were never flushed after five seconds")
485485

486486

487+
def test_user_attributes(sentry_init, capture_envelopes):
488+
"""User attributes are sent if send_default_pii is True."""
489+
sentry_init(send_default_pii=True, _experiments={"enable_logs": True})
490+
491+
sentry_sdk.set_user({"id": "1", "email": "test@example.com", "username": "test"})
492+
envelopes = capture_envelopes()
493+
494+
python_logger = logging.Logger("test-logger")
495+
python_logger.warning("Hello, world!")
496+
497+
get_client().flush()
498+
499+
logs = envelopes_to_logs(envelopes)
500+
(log,) = logs
501+
502+
# Check that all expected user attributes are present.
503+
assert log["attributes"].items() >= {
504+
("user.id", "1"),
505+
("user.email", "test@example.com"),
506+
("user.name", "test"),
507+
}
508+
509+
510+
def test_user_attributes_no_pii(sentry_init, capture_envelopes):
511+
"""Ensure no user attributes are sent if send_default_pii is False."""
512+
sentry_init(_experiments={"enable_logs": True})
513+
514+
sentry_sdk.set_user({"id": "1", "email": "test@example.com", "username": "test"})
515+
envelopes = capture_envelopes()
516+
517+
python_logger = logging.Logger("test-logger")
518+
python_logger.warning("Hello, world!")
519+
520+
get_client().flush()
521+
522+
logs = envelopes_to_logs(envelopes)
523+
524+
(log,) = logs
525+
assert "user.id" not in log["attributes"]
526+
assert "user.email" not in log["attributes"]
527+
assert "user.name" not in log["attributes"]
528+
529+
487530
@minimum_python_37
488531
def test_auto_flush_logs_after_5s(sentry_init, capture_envelopes):
489532
"""

0 commit comments

Comments
 (0)