@@ -1108,3 +1108,64 @@ Enable Loguru log capture in your |pytest|_ configuration:
11081108 See `using logot with Loguru <https://logot.readthedocs.io/latest/integrations/loguru.html >`_ for more information
11091109 about `configuring pytest <https://logot.readthedocs.io/latest/integrations/loguru.html#enabling-for-pytest >`_
11101110 and `configuring unittest <https://logot.readthedocs.io/latest/integrations/loguru.html#enabling-for-unittest >`_.
1111+
1112+ .. _add_opentelemetry_traces_id :
1113+
1114+ Add opentelemetry trace_id and span_id to json logs
1115+ ---------------------------------------------------
1116+
1117+ There is no official implementation of opentelemetry for loguru as of now, but one frequent task when integrating logs and opentelemetry
1118+ is adding the trace context to the logs to create a correlation between them.
1119+
1120+ .. code ::
1121+
1122+ from loguru import logger
1123+ import sys
1124+
1125+ from opentelemetry.trace import (
1126+ INVALID_SPAN,
1127+ INVALID_SPAN_CONTEXT,
1128+ get_current_span,
1129+ get_tracer_provider,
1130+ )
1131+
1132+
1133+ def instrument_loguru():
1134+ provider = get_tracer_provider()
1135+ service_name = None
1136+
1137+ def add_trace_context(record):
1138+ record["extra"]["otelSpanID"] = "0"
1139+ record["extra"]["otelTraceID"] = "0"
1140+ record["extra"]["otelTraceSampled"] = False
1141+
1142+ nonlocal service_name
1143+ if service_name is None:
1144+ resource = getattr(provider, "resource", None)
1145+ if resource:
1146+ service_name = resource.attributes.get("service.name") or ""
1147+ else:
1148+ service_name = ""
1149+
1150+ record["extra"]["otelServiceName"] = service_name
1151+
1152+ span = get_current_span()
1153+ if span != INVALID_SPAN:
1154+ ctx = span.get_span_context()
1155+ if ctx != INVALID_SPAN_CONTEXT:
1156+ record["extra"]["otelSpanID"] = format(ctx.span_id, "016x")
1157+ record["extra"]["otelTraceID"] = format(ctx.trace_id, "032x")
1158+ record["extra"]["otelTraceSampled"] = ctx.trace_flags.sampled
1159+
1160+ logger.configure(patcher=add_trace_context)
1161+
1162+
1163+ instrument_loguru()
1164+
1165+ logger.remove()
1166+ format_ = "{time:YYYY-MM-DD HH:MM:SS.sss} {level} [{name}] [{file}:{line} [trace_id={extra[otelTraceID]} span_id={extra[otelSpanID]} resource.service.name={extra[otelServiceName]} trace_sampled={extra[otelTraceSampled]}] - {message}"
1167+ logger.add(sys.stderr, format=format_)
1168+
1169+ logger.info("This is an info message")
1170+
1171+ Alternatively a custom formatter can be added to be able to save otelSpanID and otelTraceID in the root of the json log
0 commit comments