Skip to content

Commit 005575e

Browse files
sdk: fix ConsoleSpanExporter (#455)
19d573a ("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.
1 parent 888bed9 commit 005575e

File tree

2 files changed

+7
-2
lines changed

2 files changed

+7
-2
lines changed

Diff for: opentelemetry-sdk/src/opentelemetry/sdk/trace/export/__init__.py

+4-1
Original file line numberDiff line numberDiff line change
@@ -14,6 +14,7 @@
1414

1515
import collections
1616
import logging
17+
import os
1718
import sys
1819
import threading
1920
import typing
@@ -270,12 +271,14 @@ class ConsoleSpanExporter(SpanExporter):
270271
def __init__(
271272
self,
272273
out: typing.IO = sys.stdout,
273-
formatter: typing.Callable[[Span], str] = str,
274+
formatter: typing.Callable[[Span], str] = lambda span: str(span)
275+
+ os.linesep,
274276
):
275277
self.out = out
276278
self.formatter = formatter
277279

278280
def export(self, spans: typing.Sequence[Span]) -> SpanExportResult:
279281
for span in spans:
280282
self.out.write(self.formatter(span))
283+
self.out.flush()
281284
return SpanExportResult.SUCCESS

Diff for: opentelemetry-sdk/tests/trace/export/test_export.py

+3-1
Original file line numberDiff line numberDiff line change
@@ -12,6 +12,7 @@
1212
# See the License for the specific language governing permissions and
1313
# limitations under the License.
1414

15+
import os
1516
import time
1617
import unittest
1718
from logging import WARNING
@@ -288,8 +289,9 @@ def test_export(self): # pylint: disable=no-self-use
288289
span = trace.Span("span name", mock.Mock())
289290
with mock.patch.object(exporter, "out") as mock_stdout:
290291
exporter.export([span])
291-
mock_stdout.write.assert_called_once_with(str(span))
292+
mock_stdout.write.assert_called_once_with(str(span) + os.linesep)
292293
self.assertEqual(mock_stdout.write.call_count, 1)
294+
self.assertEqual(mock_stdout.flush.call_count, 1)
293295

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

0 commit comments

Comments
 (0)