I am trying to copy my console log to a file when running a script utilizing a snippet found on this link. I tried to customize it by adding a timestamp utilizing strftime from the time module, but the snippet now adds a timestamp to both the start of a new row and the end:
2014-12-10 12:15:35: Working on local page 12014-12-10 12:15:35:
What did I do wrong? How would I fix this so that the timestamp is only shown at the start of a newline?
from time import strftime
class copyConsoleToFile(object):
""" Enables logging of console output to a file, use
>> tlogger = copyConsoleToFile('logfile.txt', 'w')
at the start of the code to start logging.
"""
def __init__(self, name, mode):
self.file = open(name, mode)
self.stdout = sys.stdout
sys.stdout = self
def close(self):
if self.stdout is not None:
sys.stdout = self.stdout
self.stdout = None
if self.file is not None:
self.file.close()
self.file = None
def write(self, data):
self.file.write(strftime("%Y-%m-%d %H:%M:%S") + ': ' + data)
self.stdout.write(data)
def flush(self):
self.file.flush()
self.stdout.flush()
def __del__(self):
self.close()