1

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()
Community
  • 1
  • 1
MattV
  • 1,353
  • 18
  • 42

1 Answers1

0

As stated in the comments, it seems that a sub-process adds an extra write to each line. I suggest to remove the non-useful extra characters:

with open('logfile.txt','r+') as fopen:
    string = ""
    for line in fopen.readlines():
        string = string + line[:-23] + "\n"

with open('logfile.txt','w') as fopen:
    fopen.write(string)

The code was adapted from: https://stackoverflow.com/a/45594783/1751393

José Vallejo
  • 356
  • 4
  • 17