I'm using a 'Logger' class (sourced from another SO answer) in order to write to both a log file and to the terminal simultaneously whenever a print (or similar) command is used.
I've modified the logger so that it prepends all messages with a timestamp. However, it is also appending the timestamp, which is not desired. So I end up with the timestamp at both the beginning and the end of every line.
The example code below is modified to replace the actual timestamp code with the literal text "BLAH", to demonstrate that it occurs for any text, and it unrelated to the method used to obtain the timestamp.
class Logger(object):
def __init__(self):
self.terminal = sys.stdout
self.log = open(r"C:\Temp\gis_list2reference.txt", "a")
def write(self, msg):
line = "%s %s" % ("BLAH", msg)
self.terminal.write(line)
self.terminal.flush()
self.log.write(line)
self.log.flush()
## #this flush method is needed for python 3 compatibility.
## def flush(self):
## pass
sys.stdout = Logger()
print "some log text"
The output, to both the terminal and the log file, is:
BLAH some log textBLAH
How can I avoid the extra "BLAH" (or timestamp) at the end of each line logged?
Why is it getting logged?
EDIT:
As per the accepted answer below, the following code works (although it's clearly not a 'pythonic' neat way to do it:
class Logger(object):
def __init__(self):
self.terminal = sys.stdout
self.log = open(r"C:\Temp\gis_list2reference.txt", "a")
def write(self, msg):
if msg != "\n":
msg = "%s %s" % (strftime("%Y-%m-%d %H:%M:%S"), msg)
self.terminal.write(msg)
#self.terminal.flush()
self.log.write(msg)
self.log.flush()
## #this flush method is needed for python 3 compatibility.
## def flush(self):
## pass
sys.stdout = Logger()
When you are doing
print "some log test"
python will call your object twice
yourlogger.write("some log test") #this will output BLAH some log text
yourlogger.write("\n") #this will output BLAH \n
BLAH some log textoutput BLAH \n
Got it? :)
To avoid this bug you may add a special case for \n or just use a real logging.Logger :)