Skip to content

Commit 9970637

Browse files
committed
Ensure a console logging handler is registered when using logging auto-instrumentation
1 parent a7fe4f8 commit 9970637

File tree

1 file changed

+21
-4
lines changed
  • opentelemetry-sdk/src/opentelemetry/sdk/_configuration

1 file changed

+21
-4
lines changed

opentelemetry-sdk/src/opentelemetry/sdk/_configuration/__init__.py

Lines changed: 21 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -237,6 +237,7 @@ def _init_logging(
237237
exporters: Dict[str, Type[LogExporter]],
238238
resource: Resource = None,
239239
setup_logging_handler: bool = True,
240+
log_format: str = None,
240241
):
241242
provider = LoggerProvider(resource=resource)
242243
set_logger_provider(provider)
@@ -251,10 +252,25 @@ def _init_logging(
251252
set_event_logger_provider(event_logger_provider)
252253

253254
if setup_logging_handler:
254-
handler = LoggingHandler(
255-
level=logging.NOTSET, logger_provider=provider
255+
logger = logging.getLogger()
256+
logger.addHandler(
257+
LoggingHandler(level=logging.NOTSET, logger_provider=provider)
256258
)
257-
logging.getLogger().addHandler(handler)
259+
260+
# The `log_format` variable typically is read from OTEL_PYTHON_LOG_FORMAT and defaults to
261+
# logging.DEFAULT_FORMAT.
262+
if log_format:
263+
# Users of auto-instrumentation have noted that if they enable Python logging instrumentation,
264+
# their console logs disappear. This is because adding the LoggingHandler above means calls to
265+
# `logging.basicConfig()` will be no-ops, which will in turn cause logs to no longer be printed to the
266+
# console. To provide a better experience, here we explicitly set a stream (aka console) handler if
267+
# log_format is set. This causes logs to continue to be printed to the console if they request
268+
# OTEL_PYTHON_LOGGING_AUTO_INSTRUMENTATION_ENABLED, but users can control both the console log format string
269+
# via OTEL_PYTHON_LOG_FORMAT, and turn console logging off altogether by making OTEL_PYTHON_LOG_FORMAT
270+
# empty.
271+
stream_handler = logging.StreamHandler()
272+
stream_handler.setFormatter(logging.Formatter(log_format))
273+
logger.addHandler(stream_handler)
258274

259275

260276
def _import_exporters(
@@ -413,7 +429,8 @@ def _initialize_components(
413429
.lower()
414430
== "true"
415431
)
416-
_init_logging(log_exporters, resource, setup_logging_handler)
432+
log_format = os.getenv("OTEL_PYTHON_LOG_FORMAT", logging.BASIC_FORMAT)
433+
_init_logging(log_exporters, resource, setup_logging_handler, log_format)
417434

418435

419436
class _BaseConfigurator(ABC):

0 commit comments

Comments
 (0)