open-telemetry / opentelemetry-python

OpenTelemetry Python API and SDK
https://opentelemetry.io
Apache License 2.0
1.82k stars 637 forks source link

Is there a way to make loguru automatically print the trace_id in logs like logging does? #3615

Open commonfurture opened 11 months ago

commonfurture commented 11 months ago

I can print out the trace_id using the default logging, but I can't do it with loguru. Is there a way to make loguru also print out the trace_id? image

image

Rocksus commented 10 months ago

What I ended up doing was making a custom wrapper for my loguru logger, which automatically binds the traceID and spanID for me

tracing_log_format = (
    "<green>{time:YYYY-MM-DD HH:mm:ss}</green> | "
    "<level>{level: <8}</level> | "
    "<yellow>req_id:{extra[request_id]}</yellow> | "
    "<red>t:{extra[otelTraceID]} s:{extra[otelSpanID]}</red> | "
    "<cyan>{name}</cyan>:<cyan>{function}</cyan>:<cyan>{line}</cyan> - <level>{message}</level>"
    "<blue>context: {extra}</blue>"
)

logger.configure(
    extra={"otelSpanID": 0, "otelTraceID": 0}
)

logger.add(sys.stderr, format=tracing_log_format, level="INFO")

def _prepare_logger_extras() -> Dict[str, Any]:
    extra_data = {}
    span = trace.get_current_span()
    extra_data["otelSpanID"] = trace.format_span_id(
        span.get_span_context().span_id
    )
    extra_data["otelTraceID"] = trace.format_trace_id(
        span.get_span_context().trace_id
    )

    return extra_data

def info(__message: str, *args: Any, **kwargs: Any):
    logger.opt(depth=1).bind(**_prepare_logger_extras()).info(
        __message, *args, **kwargs
    )

Though I'm not sure if this can be considered good practice or not, maybe others can also help enlighten me on this

lzchen commented 9 months ago

Only the standard Python logging library is currently supported by OpenTelemetry. Converting this to a feature request to support loguru.

lzchen commented 5 months ago

Related: https://github.com/open-telemetry/opentelemetry-python/issues/3806

phitoduck commented 4 months ago

If anyone more knowledgable on Otel can comment, the creator of loguru is trying to implement this, but is held back by knowing if the behavior is close enough to what the opentelemetry-python-logging module does: https://github.com/Delgan/loguru/issues/674#issuecomment-1874389387

s71m commented 1 week ago

If someone still need it, i shared loguru handler with tracing and logging with demo examples https://github.com/s71m/opentelemetry-loguru-telegram