Log everything printed into a file
Question: I would like to create a function that keeps a record of every `print`
command, storing each command's string into a new line in a file.

    
    
    def log(line):
        with open('file.txt', "a") as f:
            f.write('\n' + line)
    

This is what I have, but is there any way to do what I said using Python?


Answer: Try replacing `stdout` with custom class:

    
    
    import sys
    class LoggedStdout():
        def __init__(self, filename = None):
            self.filename = filename
        def write(self, text):
            sys.__stdout__.write(text)
            if not self.filename is None:
                self.log(text)
        def log(self, line):
            with open(self.filename, "a") as f:
                f.write('\n' + line)
    
    sys.stdout = LoggedStdout('file.txt')
    
    print 'Hello world!'
    

This would affect not only `print`, but also any other function that prints
something to `stdout`, but it is often even better.

For production-mode logging it's much better to use something like [`logging`
module](http://docs.python.org/library/logging.html), rather than home-made
hooks over standard IO streams.

