我正在使用“记录器”类(来自另一个 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 :)
