Skip to content
This repository was archived by the owner on Oct 19, 2023. It is now read-only.

Commit d691412

Browse files
sdk: fix ConsoleSpanExporter
19d573a ("Add io and formatter options to console exporter (open-telemetry#412)") changed the way spans are printed by using write() instead of print(). In Python 3.x sys.stdout is line-buffered, so the spans were not being printed to the console at the right timing. This commit fixes that by adding an explicit flush() call at the end of the export function , it also changes the default formatter to include a line break. To be precise, only one of the changes was needed to solve the problem, but as a matter of completness both are included, i.e, to handle the case where the formatter chosen by the user doesn't append a line break.
1 parent 11467c4 commit d691412

File tree

2 files changed

+5
-2
lines changed

2 files changed

+5
-2
lines changed

opentelemetry-sdk/src/opentelemetry/sdk/trace/export/__init__.py

Lines changed: 3 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -270,12 +270,14 @@ class ConsoleSpanExporter(SpanExporter):
270270
def __init__(
271271
self,
272272
out: typing.IO = sys.stdout,
273-
formatter: typing.Callable[[Span], str] = str,
273+
formatter: typing.Callable[[Span], str] = lambda span: str(span)
274+
+ "\n",
274275
):
275276
self.out = out
276277
self.formatter = formatter
277278

278279
def export(self, spans: typing.Sequence[Span]) -> SpanExportResult:
279280
for span in spans:
280281
self.out.write(self.formatter(span))
282+
self.out.flush()
281283
return SpanExportResult.SUCCESS

opentelemetry-sdk/tests/trace/export/test_export.py

Lines changed: 2 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -288,8 +288,9 @@ def test_export(self): # pylint: disable=no-self-use
288288
span = trace.Span("span name", mock.Mock())
289289
with mock.patch.object(exporter, "out") as mock_stdout:
290290
exporter.export([span])
291-
mock_stdout.write.assert_called_once_with(str(span))
291+
mock_stdout.write.assert_called_once_with(str(span) + "\n")
292292
self.assertEqual(mock_stdout.write.call_count, 1)
293+
self.assertEqual(mock_stdout.flush.call_count, 1)
293294

294295
def test_export_custom(self): # pylint: disable=no-self-use
295296
"""Check that console exporter uses custom io, formatter."""

0 commit comments

Comments
 (0)