This is an old trick i had lost track of since i last used it. It resurfaced with the need in another program that i was writing and thought it apt to share it, and record it for my reference. It is fairly simple. But i would summarize it before we go to the script.
- Create a class to pass the instance of the stdout/stderr. Here i have chose to pass stderr.
- Open the log file to which the stderr messages need to be recorded to- should be done in the constructor.
- And then override the write method so that it writes both to the stderr and to the file.
Now you are basically done. See the follow code.
import sys
class logstderr:
"""
logstderr class is used to log any output that
is directed to the screen
"""
def __init__(self, wrfile):
"""
logstderr constructor
takes the stream that needs to be logged
"""
self.wrfile = wrfile
self.log = file("log.log","w+")
def write(self, str):
"""
To override the write of
sys.stderr.write
"""
self.wrfile.write(str)
self.log.write(str)
def __del__(self):
self.log.close()
if __name__=="__main__":
lg = logstderr(sys.stderr)
sys.stderr = lg
print >>sys.stderr,"Hello"
print >>sys.stderr,"World!"