From d14f51f3c98390d183cbf59ad1f7f87973c3107a Mon Sep 17 00:00:00 2001 From: Iuri de Silvio Date: Mon, 1 Jan 2024 10:32:53 +0100 Subject: [PATCH] Fix flush exception thrown when LoggerProvider not configured --- .../src/opentelemetry/sdk/_logs/_internal/__init__.py | 5 +++-- opentelemetry-sdk/tests/logs/test_handler.py | 6 ++++++ 2 files changed, 9 insertions(+), 2 deletions(-) diff --git a/opentelemetry-sdk/src/opentelemetry/sdk/_logs/_internal/__init__.py b/opentelemetry-sdk/src/opentelemetry/sdk/_logs/_internal/__init__.py index cfa4d6cfa9b..b6681b22d0d 100644 --- a/opentelemetry-sdk/src/opentelemetry/sdk/_logs/_internal/__init__.py +++ b/opentelemetry-sdk/src/opentelemetry/sdk/_logs/_internal/__init__.py @@ -543,9 +543,10 @@ def emit(self, record: logging.LogRecord) -> None: def flush(self) -> None: """ - Flushes the logging output. + Flushes the logging output. Skip flushing if logger is NoOp. """ - self._logger_provider.force_flush() + if not isinstance(self._logger, NoOpLogger): + self._logger_provider.force_flush() class Logger(APILogger): diff --git a/opentelemetry-sdk/tests/logs/test_handler.py b/opentelemetry-sdk/tests/logs/test_handler.py index e126cac1720..34ffef69ec7 100644 --- a/opentelemetry-sdk/tests/logs/test_handler.py +++ b/opentelemetry-sdk/tests/logs/test_handler.py @@ -79,6 +79,12 @@ def test_log_record_emit_noop(self): logger.warning("Warning message") handler_mock._translate.assert_not_called() + def test_log_flush_noop(self): + emitter_provider_mock = Mock(spec=NoOpLoggerProvider) + logger = get_logger(logger_provider=emitter_provider_mock) + with self.assertLogs(level=logging.WARNING): + logger.warning("Warning message") + def test_log_record_no_span_context(self): emitter_provider_mock = Mock(spec=LoggerProvider) emitter_mock = APIGetLogger(