mocking a logging object

Peter Bengtsson peterbe at gmail.com
Mon Jun 2 11:24:54 EDT 2008


On Jun 2, 12:34 pm, "Diez B. Roggisch" <de... at nospam.web.de> wrote:
> Peter Bengtsson wrote:
> > In my unittest I want to override the logger of a working module so
> > that it puts all logging messages in /tmp/test.log instead so that in
> > my unittest I can inspect that it logs things correctly. Hopefully
> > this "pseudo" code will explain my problem::
>
> >>>> import logging, os
> >>>> logging.basicConfig(filename='/tmp/real.log', level=logging.INFO)
> >>>> logger = logging.getLogger('Real')
> >>>> logger.info('Real stuff')
> >>>> os.path.isfile('/tmp/real.log')
> > True
> >>>> # do the monkey patching like the unit test does
> >>>> logging.basicConfig(filename='/tmp/test.log', level=logging.INFO)
> >>>> logger = logging.getLogger('Test')
> >>>> logger.info('Test stuff')
> >>>> os.path.isfile('/tmp/test.log')
> > False
> >>>> open('/tmp/real.log').read()
> > 'INFO:Real:Real stuff\nINFO:Test:Test stuff\n'
>
> > How can I change what file the logger should write to?
>
> You should simply attach a new handler to the logger in question that logs
> the data into a stream/StringIO-object for later retrieval. Then remove
> that handler after the test.
>
> Diez

Yes! That worked. Thank you.



More information about the Python-list mailing list