5

Can I redirect all output from stdout to a logger I have set up with the standard logging module? (I have os.system calls whose output I'd also like to see or occational print statements)

2
  • 2
    Duplicate of stackoverflow.com/questions/975248/… Commented Feb 23, 2012 at 10:10
  • Thanks! Somehow the automatic suggestions only showed stdout redirection to files... Commented Feb 23, 2012 at 10:20

1 Answer 1

4

You might be able to make use of the suggestion in this post, summarised 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
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.