1

我想登录到一个文本文件,无论print编辑到sys.stdout. 虽然我知道更聪明的人可以想出更优雅和 Pythonic 的解决方案,但这是我的解决方案

class logger:

  def __init__(self, filename='log.txt'):
    self.logf = open(filename, 'a')

    global print
    self.__print = print

    print = self.lognprint

  def __del__(self):
    self.logf.close()

  def lognprint(self, *args, **keywords):
    self.__print(*args, file = self.logf, **keywords)
    self.__print(*args, **keywords)

现在,如果我在代码中的任何地方添加

mylog = logger()

之后编辑的任何内容print也会被记录。

但是由于许多明显的原因,这并不安全/好。例如,多个logger对象可能很讨厌。

此外,我的灵感来自

from __future__ import print_function

(例如,请参阅this)并且我想做类似的事情,这样当我使用我的模块时,我的 print 版本会在代码中的任何位置覆盖import内置函数。print

这怎么可能?

4

2 回答 2

1

logging cookbook中给出了类似的解决方案,或者将内容记录到文件中,该文件也打印到 std.out 。
这是您可以简单地将内容记录到名为“spam.log”的文件并将某些内容打印到std.out的方法:

import logging

logger = logging.getLogger('simple_example')
logger.setLevel(logging.DEBUG)
# create file handler which logs even debug messages
fh = logging.FileHandler('spam.log')
fh.setLevel(logging.DEBUG)
# create console handler with a higher log level
ch = logging.StreamHandler()
ch.setLevel(logging.ERROR)
# create formatter and add it to the handlers
formatter = logging.Formatter('%(asctime)s - %(name)s - %(levelname)s - %(message)s')
ch.setFormatter(formatter)
fh.setFormatter(formatter)
# add the handlers to logger
logger.addHandler(ch)
logger.addHandler(fh)

# 'application' code
logger.debug('debug message')
logger.info('info message')
logger.warn('warn message')
logger.error('error message')
logger.critical('critical message')

在此示例中,所有消息都进入文件,只有更高级别进入控制台。

于 2012-09-26T20:41:45.717 回答
1

与其将代码放在类中,不如将其放在模块级别。这样它将在第一次导入模块时执行:

# logging.py
print = my_print
于 2012-09-26T20:24:01.353 回答