Skip to content Skip to sidebar Skip to footer

Python Logging To Stringio Handler

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 resp

Solution 1:

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

classMyTest(unittest.TestCase):
    defsetUp(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)
    deftestLog(self):
        self.log.info("test")
        self.handler.flush()
        print'[', self.stream.getvalue(), ']'
        self.assertEqual(self.stream.getvalue(), 'test')

    deftearDown(self):
        self.log.removeHandler(self.handler)
        self.handler.close()

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

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

Post a Comment for "Python Logging To Stringio Handler"