opentelemetry-python icon indicating copy to clipboard operation
opentelemetry-python copied to clipboard

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

Open commonfurture opened this issue 1 year ago • 4 comments

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

commonfurture avatar Jan 05 '24 02:01 commonfurture

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

Rocksus avatar Jan 18 '24 09:01 Rocksus

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

lzchen avatar Feb 16 '24 16:02 lzchen

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

lzchen avatar Jul 02 '24 19:07 lzchen

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

phitoduck avatar Jul 18 '24 17:07 phitoduck