Ask Your Question
1

How can you ensure that a handler is added only once in Python logging?

asked 2021-10-01 11:00:00 +0000

nofretete gravatar image

edit retag flag offensive close merge delete

1 Answer

Sort by ยป oldest newest most voted
0

answered 2022-12-07 05:00:00 +0000

lalupa gravatar image

You can ensure that a handler is added only once in Python logging by checking if the handler already exists in the logger and only adding it if it doesn't exist. Here's an example:

import logging

logger = logging.getLogger()
handler = logging.StreamHandler()
formatter = logging.Formatter('%(asctime)s %(levelname)-8s %(message)s')

if not any(isinstance(h, logging.StreamHandler) for h in logger.handlers):
    handler.setFormatter(formatter)
    logger.addHandler(handler)

logger.info('Hello, world!')

In this example, we first create a logger object and a handler object. We then create a formatter object and set it on the handler. We check if there are any existing handlers of the same type (in this case, a StreamHandler) in the logger, and only add the handler if there aren't any. Finally, we log a message to the logger. This ensures that the handler is added only once, even if the script is run multiple times.

edit flag offensive delete link more

Your Answer

Please start posting anonymously - your entry will be published after you log in or create a new account. This space is reserved only for answers. If you would like to engage in a discussion, please instead post a comment under the question or an answer that you would like to discuss

Add Answer


Question Tools

Stats

Asked: 2021-10-01 11:00:00 +0000

Seen: 8 times

Last updated: Dec 07 '22