#!/usr/bin/python2.4
import logging
import sys
import doctest
def foo(x):
"""
>>> foo (0)
0
"""
print ("%d" %(x))
_logger.debug("%d" %(x))
def _test():
doctest.testmod()
_logger = logging.getLogger()
_logger.setLevel(logging.DEBUG)
_formatter = logging.Formatter('%(message)s')
_handler = logging.StreamHandler(sys.stdout)
_handler.setFormatter(_formatter)
_logger.addHandler(_handler)
_test()
I would like to use logger module for all of my print statements. I have looked at the first 50 top google links for this, and they seem to agree that doctest uses it's own copy of the stdout. If print is used it works if logger is used it logs to the root console. Can someone please demonstrate a working example with a code snippet that will allow me to combine. Note running nose to test doctest will just append the log output at the end of the test, (assuming you set the switches) it does not treat them as a print statement.
OK, this is a simple one-liner that works well:
Within your doctest, before any logging capture is needed, do a
addHandler(logging.Streamhandler(sys.stdout))
on your logger. So, assuminglogger
is your logging object:Explanation: Once the doctest is running, doctest has already put its spoof in place, so
sys.stdout
is now set toDocTestRunner._fakeout
. If you create alogging.StreamHandler
for sys.stdout at this point, sys.stdout will point to doctest's spoof for sys.stdout rather than the real sys.stdout.This solution also has the advantage not depending on internal private variables in doctest, such as
_fakeout
or_SpoofOut
, in case they change in the future.If you get:
you might have forgotten to
import sys
.I'm not sure why you want to do this, but if you really need to do it, then you can define your own subclass of
DocTestRunner
, and override therun
method:Then use this runner in place of
DocTestRunner
.One simple and general-purpose approach looks like this:
The
_SpoofOut
attribute is injected by the doctest module. If it's present, you can configure logging specifically for doctest. E.g. in my example, set a verbose debug mode and log to the console.