Python Log Stdout to File

Python has the ability to alter its sys.stdout as to redirect its print commands to pretty much anything.

If, for instance, you want to print to both standard output and to a log file, you can create a class to handle the stdout like such:

class MyOutput():
    def __init__(self, logfile):
        self.stdout = sys.stdout
        self.log = open(logfile, 'w')
 
    def write(self, text):
        self.stdout.write(text)
        self.log.write(text)
        self.log.flush()
 
    def close(self):
        self.stdout.close()
        self.log.close()
 
sys.stdout = MyOutput("log.txt")
print "blah blah blah"


This class would implement stdout’s write and close functions. We then assign the stdout to an instance of this class. Inside the write/close implementations, we also add functionalities to write the texts in a log file as well. We flush the file buffer on each write because otherwise, we would only be able to see the file content when sys.stdout (therefore MyOutput) closes.

With this, outputs of print will both show in the screen and in the file log.txt

  • Nitpicker

    don’t forget:

    import sys