[Python] Python logging StreamHandler causes stack_info to print twice

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

  1. Stack

    Stack Membro Participativo

    I'm using Python 3.9 and the logging module. It seems that when I make use of a QueueHandler and the stack_info feature, the stack trace information prints twice. Anyone know how to avoid this duplication?

    This works correctly without the QueueHandler:

    import logging
    import time

    stream_handler = logging.StreamHandler ()

    lo = logging.getLogger ()
    lo.addHandler (stream_handler)

    lo.error ("This is an example error", stack_info = True)

    time.sleep (1)


    This includes the stack trace twice, and the only change I made was to insert a QueueHandler/QueueListener:

    import logging
    import logging.handlers
    import queue
    import time

    stream_handler = logging.StreamHandler ()

    q = queue.Queue (-1)
    queue_handler = logging.handlers.QueueHandler (q)

    lo = logging.getLogger ()
    lo.addHandler (queue_handler)

    queue_listener = logging.handlers.QueueListener (q, stream_handler)
    queue_listener.start ()

    lo.error ("This is an example error", stack_info = True)

    time.sleep (1)


    Output with the QueueHandler/QueueListener arrangement is the same as without, except the stack trace appears twice:

    # ./logtest-q.py
    This is an example error
    Stack (most recent call last):
    File "/home/jcharles/./logtest-q.py", line 19, in <module>
    lo.error ("This is an example error", stack_info = True)
    Stack (most recent call last):
    File "/home/jcharles/./logtest-q.py", line 19, in <module>
    lo.error ("This is an example error", stack_info = True)

    Continue reading...

Compartilhe esta Página