Skip to content

Commit

Permalink
feat: Add support for custom log levels
Browse files Browse the repository at this point in the history
  • Loading branch information
radiophysicist authored and paveldedik committed Apr 18, 2023
1 parent 317f073 commit db2b9bb
Show file tree
Hide file tree
Showing 2 changed files with 33 additions and 4 deletions.
17 changes: 16 additions & 1 deletion structlog_sentry/__init__.py
Original file line number Diff line number Diff line change
Expand Up @@ -177,6 +177,21 @@ def _handle_breadcrumb(self, event_dict: EventDict) -> None:
event, hint = self._get_breadcrumb_and_hint(event_dict)
self._get_hub().add_breadcrumb(event, hint=hint)

@staticmethod
def _get_level_value(level_name: str) -> int:
"""Get numeric value for the log level name given."""
try:
# Try to get one of predefined log levels
return getattr(logging, level_name)
except AttributeError as e:
# May be it is a custom log level?
level = logging.getLevelName(level_name)
if isinstance(level, int):
return level

# Re-raise original error
raise ValueError(f"{level_name} is not a valid log level") from e

def __call__(
self, logger: WrappedLogger, name: str, event_dict: EventDict
) -> EventDict:
Expand All @@ -185,7 +200,7 @@ def __call__(
sentry_skip = event_dict.pop("sentry_skip", False)

if self.active and not sentry_skip and self._can_record(logger, event_dict):
level = getattr(logging, event_dict["level"].upper())
level = self._get_level_value(event_dict["level"].upper())

if level >= self.event_level:
self._handle_event(event_dict)
Expand Down
20 changes: 17 additions & 3 deletions test/test_sentry_processor.py
Original file line number Diff line number Diff line change
Expand Up @@ -11,6 +11,12 @@
]


# Register custom log level
CUSTOM_LOG_LEVEL_NAME = "CUSTOM_LEVEL"
CUSTOM_LOG_LEVEL_VALUE = logging.DEBUG
logging.addLevelName(CUSTOM_LOG_LEVEL_VALUE, CUSTOM_LOG_LEVEL_NAME)


@dataclass
class ClientParams:
include_local_variables: bool = True
Expand Down Expand Up @@ -78,11 +84,19 @@ def test_sentry_sent():
assert event_dict.get("sentry") == "sent"


@pytest.mark.parametrize("level", ["debug", "info", "warning"])
def test_sentry_log(sentry_events, level):
@pytest.mark.parametrize(
"level, level_value",
[
(CUSTOM_LOG_LEVEL_NAME, CUSTOM_LOG_LEVEL_VALUE),
("debug", logging.DEBUG),
("info", logging.INFO),
("warning", logging.WARNING),
],
)
def test_sentry_log(sentry_events, level, level_value):
event_data = {"level": level, "event": level + " message"}

processor = SentryProcessor(event_level=getattr(logging, level.upper()))
processor = SentryProcessor(event_level=level_value)
processor(None, None, event_data)

assert_event_dict(event_data, sentry_events)
Expand Down

0 comments on commit db2b9bb

Please sign in to comment.