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
.
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: 2022-07-22 11:00:00 +0000
Seen: 8 times
Last updated: Jun 16 '21
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?