Ask Your Question
2

How can the default handler of Python logger be substituted?

asked 2022-07-22 11:00:00 +0000

pufferfish gravatar image

edit retag flag offensive close merge delete

1 Answer

Sort by ยป oldest newest most voted
2

answered 2021-06-16 15:00:00 +0000

scrum gravatar image

The default handler of the Python logger can be substituted by creating a new handler object and adding it to the logger instance.

Here's an example:

import logging

# Create a new handler object
handler = logging.FileHandler('mylog.log')

# Set the formatter for the handler
formatter = logging.Formatter('%(asctime)s %(levelname)s %(message)s')
handler.setFormatter(formatter)

# Get the root logger and remove the old handler
root_logger = logging.getLogger()
for old_handler in root_logger.handlers:
    root_logger.removeHandler(old_handler)

# Add the new handler to the root logger
root_logger.addHandler(handler)

In this example, a new FileHandler object is created and a formatter is set for it. The existing handlers of the root logger are then removed using a for loop, and the new handler is added to the root logger using the addHandler method.

After this code is executed, any logging calls made using the default logger will be handled by the new FileHandler.

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: 2022-07-22 11:00:00 +0000

Seen: 8 times

Last updated: Jun 16 '21