From 46cf5b5257d371dc827c7fa50a649ef8c66dfedc Mon Sep 17 00:00:00 2001 From: Andre Murbach Maidl Date: Fri, 21 Mar 2025 13:33:51 -0300 Subject: [PATCH] Add instrumentation example to logging (#3314) MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit * Add instrumentation example to logging * Add example output to logging instrumentation example * Fix logging instrumentation example and output * Fixing rst syntax for logging instrumentation examples --------- Co-authored-by: Emídio Neto <9735060+emdneto@users.noreply.github.com> Co-authored-by: Riccardo Magliocchetti --- .../instrumentation/logging/__init__.py | 41 +++++++++++++++++++ 1 file changed, 41 insertions(+) diff --git a/instrumentation/opentelemetry-instrumentation-logging/src/opentelemetry/instrumentation/logging/__init__.py b/instrumentation/opentelemetry-instrumentation-logging/src/opentelemetry/instrumentation/logging/__init__.py index 35d202215..226108325 100644 --- a/instrumentation/opentelemetry-instrumentation-logging/src/opentelemetry/instrumentation/logging/__init__.py +++ b/instrumentation/opentelemetry-instrumentation-logging/src/opentelemetry/instrumentation/logging/__init__.py @@ -14,6 +14,47 @@ # pylint: disable=empty-docstring,no-value-for-parameter,no-member,no-name-in-module +""" +The OpenTelemetry `logging` integration automatically injects tracing context into +log statements, though it is opt-in and must be enabled explicitly by setting the +environment variable `OTEL_PYTHON_LOG_CORRELATION` to `true`. + +.. code-block:: python + + import logging + + from opentelemetry.instrumentation.logging import LoggingInstrumentor + + LoggingInstrumentor().instrument() + + logging.warning('OTel test') + +When running the above example you will see the following output: + +:: + + 2025-03-05 09:40:04,398 WARNING [root] [example.py:7] [trace_id=0 span_id=0 resource.service.name= trace_sampled=False] - OTel test + +The environment variable `OTEL_PYTHON_LOG_CORRELATION` must be set to `true` +in order to enable trace context injection into logs by calling +`logging.basicConfig()` and setting a logging format that makes use of the +injected tracing variables. + +Alternatively, `set_logging_format` argument can be set to `True` when +initializing the `LoggingInstrumentor` class to achieve the same effect: + +.. code-block:: python + + import logging + + from opentelemetry.instrumentation.logging import LoggingInstrumentor + + LoggingInstrumentor().instrument(set_logging_format=True) + + logging.warning('OTel test') + +""" + import logging # pylint: disable=import-self from os import environ from typing import Collection