Python 记录到标准输出和 StringIO

Python logging to stdout and StringIO

尝试[see it running here]:

from sys import stdout, stderr
from cStringIO import StringIO
from logging import getLogger, basicConfig, StreamHandler

basicConfig(format='%(asctime)s %(name)-12s %(levelname)-8s %(message)s',
            datefmt='%m-%d %H:%M')

log = getLogger(__name__)
sio = StringIO()
console = StreamHandler(sio)

log.addHandler(console)
log.addHandler(StreamHandler(stdout))

log.info('Jackdaws love my big sphinx of quartz.')
print 'console.stream.read() = {!r}'.format(console.stream.read())

输出[标准输出]:

console.stream.read() = ''

预期输出[标准输出]:

[date] [filename] INFO Jackdaws love my big sphinx of quartz.
console.stream.read() = 'Jackdaws love my big sphinx of quartz.'

这里发生了两件事。

首先,根记录器被实例化为WARNING级别,这意味着级别低于WARNING的消息将不会被处理。您可以使用 Logger.setLevel(level) 设置级别,此处定义级别 - https://docs.python.org/2/library/logging.html#levels.

如评论中所建议,日志级别也可以设置为:

basicConfig(level='INFO', ...)

其次,当你写入StringIO对象时,流中的位置被设置在当前流的末尾。您需要倒回 StringIO 对象,然后才能从中读取。

console.stream.seek(0)
console.stream.read()

更简单,直接调用:

console.stream.getvalue()

完整代码:

from sys import stdout, stderr
from cStringIO import StringIO
from logging import getLogger, basicConfig, StreamHandler

basicConfig(format='%(asctime)s %(name)-12s %(levelname)-8s %(message)s',
            datefmt='%m-%d %H:%M')

log = getLogger(__name__)
log.setLevel("INFO")
sio = StringIO()
console = StreamHandler(sio)

log.addHandler(console)
log.addHandler(StreamHandler(stdout))

log.info('Jackdaws love my big sphinx of quartz.')
console.stream.seek(0)
print 'console.stream.read() = {!r}'.format(console.stream.read())