Skip to content

Commit bb56977

Browse files
beniwohligusibi
andcommitted
log error when trying to end a span that hasn't started (#229)
Usually, this shouldn't happen and is an indication of a bug. But we should still ensure that we don't crash and instead log a message. fixes #227 closes #229 Co-authored-by: goodspeed <[email protected]>
1 parent 2702c40 commit bb56977

File tree

2 files changed

+18
-1
lines changed

2 files changed

+18
-1
lines changed

elasticapm/traces.py

Lines changed: 4 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -268,7 +268,10 @@ def __enter__(self):
268268
def __exit__(self, exc_type, exc_val, exc_tb):
269269
transaction = get_transaction()
270270
if transaction and transaction.is_sampled:
271-
transaction.end_span(self.skip_frames)
271+
try:
272+
transaction.end_span(self.skip_frames)
273+
except IndexError:
274+
error_logger.info('ended non-existing span %s of type %s', self.name, self.type)
272275

273276

274277
def tag(**tags):

tests/instrumentation/base_tests.py

Lines changed: 14 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1,4 +1,5 @@
11
# -*- coding: utf-8 -*-
2+
import logging
23
import types
34

45
import mock
@@ -110,3 +111,16 @@ def test_skip_ignored_frames(elasticapm_client):
110111
transaction = elasticapm_client.end_transaction('test', 'test')
111112
for frame in transaction.spans[0].frames:
112113
assert not frame['module'].startswith('elasticapm')
114+
115+
116+
def test_end_nonexisting_span(caplog, elasticapm_client):
117+
with caplog.at_level(logging.INFO):
118+
t = elasticapm_client.begin_transaction('test')
119+
# we're purposefully creating a case where we don't begin a span
120+
# and then try to end the non-existing span
121+
t.is_sampled = False
122+
with elasticapm.capture_span('test_name', 'test_type'):
123+
t.is_sampled = True
124+
elasticapm_client.end_transaction('test', '')
125+
record = caplog.records[0]
126+
assert record.args == ('test_name', 'test_type')

0 commit comments

Comments
 (0)