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.
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
Asked: 2021-10-01 11:00:00 +0000
Seen: 8 times
Last updated: Dec 07 '22
How can I set up Gunicorn with a Django Project?
Looking for a Python Module that finds Tags for a Text describing its Content
Need a Function in Python to remove entries less than 2 digits from an Array
How can I convert a Document in Python?
How can I program a Loop in Python?
How can I enable Python Code Highlighting in Askbot?