Skip to content

Commit 19d573a

Browse files
c24tocelotl
andauthored
Add io and formatter options to console exporter (open-telemetry#412)
Co-authored-by: Diego Hurtado <ocelotl@users.noreply.github.com>
1 parent 2a54a93 commit 19d573a

File tree

2 files changed

+38
-1
lines changed

2 files changed

+38
-1
lines changed

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

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

1515
import collections
1616
import logging
17+
import sys
1718
import threading
1819
import typing
1920
from enum import Enum
@@ -266,7 +267,15 @@ class ConsoleSpanExporter(SpanExporter):
266267
spans to the console STDOUT.
267268
"""
268269

270+
def __init__(
271+
self,
272+
out: typing.IO = sys.stdout,
273+
formatter: typing.Callable[[Span], str] = str,
274+
):
275+
self.out = out
276+
self.formatter = formatter
277+
269278
def export(self, spans: typing.Sequence[Span]) -> SpanExportResult:
270279
for span in spans:
271-
print(span)
280+
self.out.write(self.formatter(span))
272281
return SpanExportResult.SUCCESS

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

+28
Original file line numberDiff line numberDiff line change
@@ -276,3 +276,31 @@ def test_batch_span_processor_parameters(self):
276276
max_queue_size=256,
277277
max_export_batch_size=512,
278278
)
279+
280+
281+
class TestConsoleSpanExporter(unittest.TestCase):
282+
def test_export(self): # pylint: disable=no-self-use
283+
"""Check that the console exporter prints spans."""
284+
exporter = export.ConsoleSpanExporter()
285+
286+
# Mocking stdout interferes with debugging and test reporting, mock on
287+
# the exporter instance instead.
288+
span = trace.Span("span name", mock.Mock())
289+
with mock.patch.object(exporter, "out") as mock_stdout:
290+
exporter.export([span])
291+
mock_stdout.write.assert_called_once_with(str(span))
292+
self.assertEqual(mock_stdout.write.call_count, 1)
293+
294+
def test_export_custom(self): # pylint: disable=no-self-use
295+
"""Check that console exporter uses custom io, formatter."""
296+
mock_span_str = mock.Mock(str)
297+
298+
def formatter(span): # pylint: disable=unused-argument
299+
return mock_span_str
300+
301+
mock_stdout = mock.Mock()
302+
exporter = export.ConsoleSpanExporter(
303+
out=mock_stdout, formatter=formatter
304+
)
305+
exporter.export([trace.Span("span name", mock.Mock())])
306+
mock_stdout.write.assert_called_once_with(mock_span_str)

0 commit comments

Comments
 (0)