[Python] logging: print message only once

Discussão em 'Python' iniciado por Stack, Março 6, 2025.

  1. Stack

    Stack Membro Participativo

    I'm using the logging module in python 3, and want a particular warning message to be displayed only once. The problem is that the check is inside a loop:

    def canned_example():
    logger.warning("This function hasn't been created yet")


    for i in range(10):
    canned_example()


    Is there a flag to set inside the logging module that will denote that this particular warning is only to be displayed once? The alternative is to keep a record of different flags, but I'd like to keep it simple if possible.

    Update: Amir Yazdanbakhsh has posted an answer in the comments that allows us to do this for all messages. Ideally, I'd like some per-message flag:

    def canned_example():
    logger.warning("This function hasn't been created yet", norepeat=True)


    for i in range(10):
    canned_example()

    Continue reading...

Compartilhe esta Página