Redirect stdout to logger in Python

Is it possible to redirect all the output from stdoutto the log that I installed with the standard module logging? (I have os.system calls, the output of which I would also like to see or print occlusal statements)

+5
source share
1 answer

You might be able to use the offer in this post below:

import logging

class LoggerWriter:
    def __init__(self, logger, level):
        self.logger = logger
        self.level = level

    def write(self, message):
        if message != '\n':
            self.logger.log(self.level, message)

def main():
    logging.basicConfig(level=logging.DEBUG)
    logger = logging.getLogger("demo")
    info_fp = LoggerWriter(logger, logging.INFO)
    debug_fp = LoggerWriter(logger, logging.DEBUG)
    print >> info_fp, "An INFO message"
    print >> debug_fp, "A DEBUG message"

if __name__ == "__main__":
    main()

When run, the script prints:

INFO:demo:An INFO message
DEBUG:demo:An DEBUG message
+4
source

All Articles