Python 记录到标准输出和 StringIO

标签 python python-2.7 logging stdout 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.'

最佳答案

这里发生了两件事。

首先,root logger 被实例化为 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())

关于Python 记录到标准输出和 StringIO,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41215236/

相关文章:

python - Numba 的 jit 无法编译具有另一个函数作为输入的函数

python - PyCharm 模块导入错误

python - 如何在 Python 中优化多处理

python - 如何在我的 python 代码中使用修改后的 openssl 库(用 C 编写)?

python - Shebang/选择脚本要运行的 Python 版本

c++ - 用于 C++ 的进程安全日志库

python - 在数据框中添加字典作为新行

python-2.7 - 如何使用 MS Visual Studio 2015 中的命令行参数运行 python 脚本

javascript - winston Elasticsearch : TypeError: Elasticsearch is not a constructor

sql-server - bigint 对于事件日志表来说足够大吗?