Ask Your Question
3

How can the stdout of Python's 'print' function be redirected to a Logger?

asked 2023-06-10 16:15:26 +0000

david gravatar image

edit retag flag offensive close merge delete

1 Answer

Sort by ยป oldest newest most voted
0

answered 2023-06-10 16:31:01 +0000

bukephalos gravatar image

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.

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: 2023-06-10 16:15:26 +0000

Seen: 18 times

Last updated: Jun 10 '23