【问题标题】:Python 'Logger' class repeats timestampPython 'Logger' 类重复时间戳
【发布时间】:2016-01-06 22:53:44
【问题描述】:

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

【问题讨论】:

  • 使用Python自带的日志模块。创建一个记录器并注册一个流处理程序和一个文件处理程序。你正在做的不是解决问题的pythonic方法
  • @brunsgaard 是正确的。使用logging
  • 据我所知,日志模块似乎没有写入终端(从快速浏览文档)。我需要为每个“打印”(或等效项)写入终端和日志文件。日志模块可以做到这一点吗?

标签: python logging stdout stderr


【解决方案1】:

当你在做的时候

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

【讨论】:

  • 所以“打印”命令对“\n”使用了单独的调用?我没有意识到这一点。你的答案似乎是正确的。我想我还需要调查记录器类。
  • @SonofaBeach 酷,然后接受它:)。我也认为最pythonic的方式是日志模块......
  • 我同意这不是最 Pythonic 的方式,但是(如上所述)日志模块是否提供了同时为每个“打印”(或等效项)同时记录到终端和日志文件的功能)?
  • 是的,请参考日志模块文档以获取极好的示例
猜你喜欢
  • 2015-11-09
  • 2013-02-09
  • 1970-01-01
  • 2019-10-19
  • 2018-05-20
  • 2012-01-23
  • 2014-08-13
  • 2020-03-01
相关资源
最近更新 更多