Skip to content

Commit ea8c77a

Browse files
authored
Skip formatting log records when Sentry logs are off (#7422)
`SentryLogsHandler.emit` called `format()` before checking whether logs are enabled. Every stdlib record paid for a Formatter even with the feature off. Format after the capture check. Fixes #7402
1 parent 6554607 commit ea8c77a

2 files changed

Lines changed: 19 additions & 1 deletion

File tree

‎sentry_sdk/integrations/logging.py‎

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -395,7 +395,6 @@ def _can_record(self, record: "LogRecord") -> bool:
395395

396396
def emit(self, record: "LogRecord") -> "Any":
397397
with capture_internal_exceptions():
398-
self.format(record)
399398
if not self._can_record(record):
400399
return
401400

@@ -420,6 +419,7 @@ def emit(self, record: "LogRecord") -> "Any":
420419
if not should_capture_logs:
421420
return
422421

422+
self.format(record)
423423
self._capture_log_from_record(client, record)
424424

425425
def _capture_log_from_record(

‎tests/integrations/logging/test_logging.py‎

Lines changed: 18 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -8,6 +8,7 @@
88
from sentry_sdk.consts import VERSION
99
from sentry_sdk.integrations.logging import (
1010
LoggingIntegration,
11+
SentryLogsHandler,
1112
ignore_logger,
1213
ignore_logger_for_sentry_logs,
1314
unignore_logger,
@@ -244,6 +245,23 @@ def test_sentry_logs_collection_off_by_default(sentry_init, capture_items, reque
244245
assert not items
245246

246247

248+
def test_sentry_logs_handler_skips_format_when_disabled(sentry_init):
249+
sentry_init(integrations=[LoggingIntegration(capture_sentry_logs=False)])
250+
handler = SentryLogsHandler()
251+
record = logging.LogRecord(
252+
name="test-logger",
253+
level=logging.INFO,
254+
pathname=__file__,
255+
lineno=1,
256+
msg="hello %s",
257+
args=("world",),
258+
exc_info=None,
259+
)
260+
with mock.patch.object(handler, "format") as formatted:
261+
handler.emit(record)
262+
formatted.assert_not_called()
263+
264+
247265
def test_sentry_logs_collection_opt_in(sentry_init, capture_items, request):
248266
"""Automatic logs capture by Sentry logs needs explicit opt-in via capture_sentry_logs."""
249267
sentry_init(integrations=[LoggingIntegration(capture_sentry_logs=True)])

0 commit comments

Comments
 (0)