feat(logger): Add trace_id and span_id to log

Signed-off-by: Adam Tao <tcx4c70@gmail.com>
This commit is contained in:
Adam Tao 2025-06-18 18:48:47 +08:00
parent 37c2fb0aa8
commit 739098ab60

View file

@ -4,6 +4,7 @@ import sys
from typing import TYPE_CHECKING
from loguru import logger
from opentelemetry import trace
from open_webui.env import (
@ -12,6 +13,7 @@ from open_webui.env import (
AUDIT_LOG_LEVEL,
AUDIT_LOGS_FILE_PATH,
GLOBAL_LOG_LEVEL,
ENABLE_OTEL,
)
@ -60,9 +62,20 @@ class InterceptHandler(logging.Handler):
frame = frame.f_back
depth += 1
logger.opt(depth=depth, exception=record.exc_info).log(
level, record.getMessage()
)
logger.opt(depth=depth, exception=record.exc_info).bind(
**self._get_extras()
).log(level, record.getMessage())
def _get_extras(self):
if not ENABLE_OTEL:
return {}
extras = {}
context = trace.get_current_span().get_span_context()
if context.is_valid:
extras["trace_id"] = trace.format_trace_id(context.trace_id)
extras["span_id"] = trace.format_span_id(context.span_id)
return extras
def file_format(record: "Record"):