Python 'Logger' class 重复时间戳

Python 'Logger' class repeats timestamp

我正在使用 'Logger' class(来自另一个 SO 答案)以便在打印(或类似)命令时同时写入日志文件和终端使用过。

我修改了记录器,以便它在所有消息前加上时间戳。但是,它还会附加时间戳,这是不需要的。所以我在每一行的开头和结尾都得到了时间戳。

下面的示例代码被修改为用文字文本替换实际的时间戳代码"BLAH",以证明它出现在任何文本中,并且与用于获取时间戳的方法无关。

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"

终端和日志文件的输出是:

BLAH  some log textBLAH

如何避免在记录的每行末尾出现额外的 "BLAH"(或时间戳)?

为什么会被记录?

编辑:

根据下面接受的答案,以下代码有效(尽管它显然不是 'pythonic' 的巧妙方法:

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()

当你在做的时候

print "some log test"

python 将调用您的对象两次

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

明白了吗? :)

为避免此错误,您可以为 \n 添加一个特殊情况或只使用真正的 logging.Logger :)