Skip to content

Commit ec07fa7

Browse files
authored
Skip recording exceptions on NonRecordingSpan (#1497)
1 parent c82a1c7 commit ec07fa7

File tree

3 files changed

+22
-4
lines changed

3 files changed

+22
-4
lines changed

logfire/_internal/main.py

Lines changed: 3 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -758,6 +758,9 @@ def log(
758758
start_time=start_time,
759759
)
760760

761+
if not span.is_recording():
762+
return
763+
761764
if exc_info:
762765
if exc_info is True:
763766
exc_info = sys.exc_info()
@@ -2479,10 +2482,6 @@ def record_exception(
24792482
if self._span is None:
24802483
raise RuntimeError('Span has not been started')
24812484

2482-
# Check if the span has been sampled out first, since _record_exception is somewhat expensive.
2483-
if not self._span.is_recording():
2484-
return
2485-
24862485
self._span.record_exception(
24872486
exception,
24882487
attributes=attributes,

logfire/_internal/tracer.py

Lines changed: 3 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -422,6 +422,9 @@ def record_exception(
422422
"""Similar to the OTEL SDK Span.record_exception method, with our own additions."""
423423
from ..types import ExceptionCallbackHelper
424424

425+
if not span.is_recording():
426+
return
427+
425428
if is_starlette_http_exception(exception):
426429
if 400 <= exception.status_code < 500:
427430
# Don't mark 4xx HTTP exceptions as errors, they are expected to happen in normal operation.

tests/test_exceptions.py

Lines changed: 16 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -349,3 +349,19 @@ def exception_callback(helper: ExceptionCallbackHelper) -> None:
349349
}
350350
]
351351
)
352+
353+
354+
def test_nonrecording_span(exporter: TestExporter, config_kwargs: dict[str, Any]):
355+
config_kwargs['sampling'] = logfire.SamplingOptions(head=0)
356+
logfire.configure(**config_kwargs)
357+
358+
with pytest.raises(ValueError):
359+
with logfire.span('span') as span:
360+
try:
361+
raise ValueError('test')
362+
except ValueError as e:
363+
span.record_exception(e)
364+
logfire.exception('span exception')
365+
raise
366+
367+
assert exporter.exported_spans_as_dict() == snapshot([])

0 commit comments

Comments
 (0)