From 005575e537ff97f345610c92276d6b55c32e65e5 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Mauricio=20V=C3=A1squez?= Date: Wed, 4 Mar 2020 00:01:56 -0500 Subject: [PATCH] sdk: fix ConsoleSpanExporter (#455) 19d573af0275 ("Add io and formatter options to console exporter (#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. --- .../src/opentelemetry/sdk/trace/export/__init__.py | 5 ++++- opentelemetry-sdk/tests/trace/export/test_export.py | 4 +++- 2 files changed, 7 insertions(+), 2 deletions(-) diff --git a/opentelemetry-sdk/src/opentelemetry/sdk/trace/export/__init__.py b/opentelemetry-sdk/src/opentelemetry/sdk/trace/export/__init__.py index 0f96808ea88..e5d96eff9e9 100644 --- a/opentelemetry-sdk/src/opentelemetry/sdk/trace/export/__init__.py +++ b/opentelemetry-sdk/src/opentelemetry/sdk/trace/export/__init__.py @@ -14,6 +14,7 @@ import collections import logging +import os import sys import threading import typing @@ -270,7 +271,8 @@ class ConsoleSpanExporter(SpanExporter): def __init__( self, out: typing.IO = sys.stdout, - formatter: typing.Callable[[Span], str] = str, + formatter: typing.Callable[[Span], str] = lambda span: str(span) + + os.linesep, ): self.out = out self.formatter = formatter @@ -278,4 +280,5 @@ def __init__( def export(self, spans: typing.Sequence[Span]) -> SpanExportResult: for span in spans: self.out.write(self.formatter(span)) + self.out.flush() return SpanExportResult.SUCCESS diff --git a/opentelemetry-sdk/tests/trace/export/test_export.py b/opentelemetry-sdk/tests/trace/export/test_export.py index e1c709719a3..cedb5967666 100644 --- a/opentelemetry-sdk/tests/trace/export/test_export.py +++ b/opentelemetry-sdk/tests/trace/export/test_export.py @@ -12,6 +12,7 @@ # See the License for the specific language governing permissions and # limitations under the License. +import os import time import unittest from logging import WARNING @@ -288,8 +289,9 @@ def test_export(self): # pylint: disable=no-self-use span = trace.Span("span name", mock.Mock()) with mock.patch.object(exporter, "out") as mock_stdout: exporter.export([span]) - mock_stdout.write.assert_called_once_with(str(span)) + mock_stdout.write.assert_called_once_with(str(span) + os.linesep) self.assertEqual(mock_stdout.write.call_count, 1) + self.assertEqual(mock_stdout.flush.call_count, 1) def test_export_custom(self): # pylint: disable=no-self-use """Check that console exporter uses custom io, formatter."""