Python' Logger' class重复时间戳

时间:2016-01-06 22:53:45

标签: python logging stdout stderr

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

我修改了记录器,以便它为所有带有时间戳的消息添加前缀。但是,它还附加了时间戳,这是不希望的。所以我最终得到了每行开头和结尾的时间戳。

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

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

1 个答案:

答案 0 :(得分:2)

当你做的时候

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一些日志文本输出BLAH \ n

  

知道了吗? :)

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

相关问题