Skip to content

Commit

Permalink
sdk: fix ConsoleSpanExporter (#455)
Browse files Browse the repository at this point in the history
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.
  • Loading branch information
mauriciovasquezbernal committed Mar 4, 2020
1 parent 888bed9 commit 005575e
Show file tree
Hide file tree
Showing 2 changed files with 7 additions and 2 deletions.
Original file line number Diff line number Diff line change
Expand Up @@ -14,6 +14,7 @@

import collections
import logging
import os
import sys
import threading
import typing
Expand Down Expand Up @@ -270,12 +271,14 @@ 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

def export(self, spans: typing.Sequence[Span]) -> SpanExportResult:
for span in spans:
self.out.write(self.formatter(span))
self.out.flush()
return SpanExportResult.SUCCESS
4 changes: 3 additions & 1 deletion opentelemetry-sdk/tests/trace/export/test_export.py
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand Down Expand Up @@ -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."""
Expand Down

0 comments on commit 005575e

Please sign in to comment.