From 2a1de6ab9d00d024dc9cbe043e5400e3e91c8088 Mon Sep 17 00:00:00 2001 From: Alexander Micklewright Date: Thu, 8 Aug 2019 17:52:58 +0200 Subject: [PATCH] Add user event data from logging extra --- sentry_sdk/integrations/logging.py | 9 ++++++++ tests/integrations/logging/test_logging.py | 26 ++++++++++++++++++++++ 2 files changed, 35 insertions(+) diff --git a/sentry_sdk/integrations/logging.py b/sentry_sdk/integrations/logging.py index 512c3dada5..92eaa3c70e 100644 --- a/sentry_sdk/integrations/logging.py +++ b/sentry_sdk/integrations/logging.py @@ -145,6 +145,14 @@ def _extra_from_record(record): } +def _user_from_record(record): + # type: (LogRecord) -> Optional[Dict[str, None]] + user = vars(record).get("user") + if not isinstance(user, dict): + return None + return user + + class EventHandler(logging.Handler, object): def emit(self, record): # type: (LogRecord) -> Any @@ -194,6 +202,7 @@ def _emit(self, record): event["level"] = _logging_to_event_level(record.levelname) event["logger"] = record.name event["logentry"] = {"message": to_string(record.msg), "params": record.args} + event["user"] = _user_from_record(record) event["extra"] = _extra_from_record(record) hub.capture_event(event, hint=hint) diff --git a/tests/integrations/logging/test_logging.py b/tests/integrations/logging/test_logging.py index c068c40fda..114705998e 100644 --- a/tests/integrations/logging/test_logging.py +++ b/tests/integrations/logging/test_logging.py @@ -72,6 +72,32 @@ def test_logging_extra_data_integer_keys(sentry_init, capture_events): assert event["extra"] == {"1": 1} +def test_logging_user_data(sentry_init, capture_events): + sentry_init(integrations=[LoggingIntegration()], default_integrations=False) + events = capture_events() + + logger.critical( + "User error", extra=dict(user=dict(id=123, email="user@example.org")) + ) + + event, = events + + assert event["user"]["id"] == 123 + assert event["user"]["email"] == "user@example.org" + + +def test_logging_invalid_user_data(sentry_init, capture_events): + sentry_init(integrations=[LoggingIntegration()], default_integrations=False) + events = capture_events() + + logger.critical("User error", extra=dict(user=123)) + + event, = events + + assert "user" not in event + assert event["extra"]["user"] == 123 + + @pytest.mark.xfail(sys.version_info[:2] == (3, 4), reason="buggy logging module") def test_logging_stack(sentry_init, capture_events): sentry_init(integrations=[LoggingIntegration()], default_integrations=False)