[Python] Using Python's logging module to record trace_id

Discussão em 'Python' iniciado por Stack, Fevereiro 21, 2025.

  1. Stack

    Stack Membro Participativo

    My program imports a library and only uses one function from it called do_stuff(). The library has loggers set up the usual way in each of its modules. The main program also has loggers set up the same way.

    import logging
    logger = logging.getLogger(__name__)


    I want to prepend a trace_id to the library's logs only for easier retrieval in the future. All of library logs should have the same ID prepended for each call. For example, it should look something like:

    [INFO] log in main program
    [INFO] [abcdef] first log in library call 1
    [INFO] [abcdef] second log in library call 1
    [INFO] [abcdef] third log in library call 1
    [INFO] back to main
    [INFO] [qwerty] first log in library call 2
    [INFO] [qwerty] second log in library call 2
    [INFO] [qwerty] third log in library call 2
    [INFO] program end


    I looked into opentelemetry's python implementation but it seems unnecessarily complex for my purposes. I also tried using Custom logger class but can't seem to get it to work.

    Continue reading...

Compartilhe esta Página