Python记录到StringIO处理程序 [英] Python logging to StringIO handler

查看:191
本文介绍了Python记录到StringIO处理程序的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个python测试,我想在其中测试日志记录是否正常工作.例如,我有一个创建用户的函数,最后日志记录将响应写入日志文件.

I have a python test in which I want to test if the logging works properly. For example I have a function that creates a user and at the end the logging writes to log file the response.

logger = logging.getLogger('mylogger')
logger.setLevel(logging.DEBUG)
handler = logging.handlers.WatchedFileHandler('mylogfile.log')
formatter = logging.Formatter('%(asctime)s: %(message)s',
                              '%d/%b/%Y:%H:%M:%S %z')
handler.setFormatter(formatter)
logger.addHandler(handler)
logger.info('Some log text')

在我的测试案例中,我想将日志输出发送到StringIO.

In my test case I want to send the log output to the StringIO.

class MyTest(unittest.TestCase):
    def setUp(self):
        stream = StringIO()
        self.handler = logging.StreamHandler(stream)
        log = logging.getLogger('mylogger')
        log.removeHandler(log.handlers[0])
        log.addHandler(self.handler)

    def tearDown(self):
        log = logging.getLogger('mylogger')
        log.removeHandler(self.handler)
        self.handler.close()

问题是我不确定应该如何测试记录仪是否正常工作.

The problem is that I'm not sure how should I test wheter or not my logger is working.

推荐答案

下面是一个有效的示例,请确保设置日志级别并刷新缓冲区.

Here is an example that works, make sure you set the level of your log, and flush the buffer.

class MyTest(unittest.TestCase):
    def setUp(self):
        self.stream = StringIO()
        self.handler = logging.StreamHandler(self.stream)
        self.log = logging.getLogger('mylogger')
        self.log.setLevel(logging.INFO)
        for handler in self.log.handlers: 
            self.log.removeHandler(handler)
        self.log.addHandler(self.handler)
    def testLog(self):
        self.log.info("test")
        self.handler.flush()
        print '[', self.stream.getvalue(), ']'
        self.assertEqual(self.stream.getvalue(), 'test')

    def tearDown(self):
        self.log.removeHandler(self.handler)
        self.handler.close()

if __name__=='__main__':
    unittest.main()

进一步阅读,这是一个示例暂时捕获Python登录到字符串缓冲区,该字符串显示了如何进行格式化.

Further reading, here is an example Temporily Capturing Python Logging to a string buffer that show how you could also do formatting.

这篇关于Python记录到StringIO处理程序的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆