The stdout of Python's 'print' function can be redirected to a logger by defining a custom logging handler that redirects the output to the desired logger. Here's an example:
import logging
class PrintLogger(logging.Handler):
def emit(self, record):
msg = self.format(record)
logger = logging.getLogger(record.name)
logger.info(msg)
print_logger = logging.getLogger('print_logger')
print_logger.setLevel(logging.INFO)
print_logger.addHandler(PrintLogger())
# Redirect stdout to print_logger
import sys
sys.stdout = print_logger
# Test print statement
print('Hello, world!')
In this example, a custom logging handler named PrintLogger
is defined that redirects the output to the desired logger. It is then added as a handler to a new logger named print_logger
, which is then used to redirect the standard output (stdout) via the sys.stdout
variable. When a print
statement is executed, its output is redirected to PrintLogger
, which then logs the message to the print_logger
logger.
Asked: 2023-06-10 16:15:26 +0000
Seen: 18 times
Last updated: Jun 10 '23