是否有一个模块可以记录内存中的错误?

时间:2014-04-01 10:53:55

标签: python python-2.7 logging

所以我想在内存中记录错误(我不想写任何日志文件)并稍后访问它们以在程序执行后以批量形式显示它们。 它看起来像是:

...
Program executing ...
...
Errors occured !
Error 1 : ...
Error 2 : ...

我不是在问自己该如何做,而是如果一些现有的模块能够做到这一点。我想尽可能使用标准模块。

1 个答案:

答案 0 :(得分:6)

您可以将StringIO缓冲区传递给标准日志记录模块的StreamHandler

import logging, StringIO

print 'Setting up logging ...'
stream = StringIO.StringIO()
log = logging.getLogger()
handler = logging.StreamHandler(stream)
log.addHandler(handler)

print 'Starting main program ...'
log.warning('This is serious')
log.error('This is really bad')

print 'Finished main, printing log messages ...'
print stream.getvalue()

预期结果:

Setting up logging ...
Starting main program ...
Finished main, printing log messages ...
This is serious
This is really bad