Python logging to stdout and StringIO

2.6k views Asked by At

Attempt [see it running here]:

from sys import stdout, stderr
from cStringIO import StringIO
from logging import getLogger, basicConfig, StreamHandler

basicConfig(format='%(asctime)s %(name)-12s %(levelname)-8s %(message)s',
            datefmt='%m-%d %H:%M')

log = getLogger(__name__)
sio = StringIO()
console = StreamHandler(sio)

log.addHandler(console)
log.addHandler(StreamHandler(stdout))

log.info('Jackdaws love my big sphinx of quartz.')
print 'console.stream.read() = {!r}'.format(console.stream.read())

Output [stdout]:

console.stream.read() = ''

Expected output [stdout]:

[date] [filename] INFO Jackdaws love my big sphinx of quartz.
console.stream.read() = 'Jackdaws love my big sphinx of quartz.'
1

There are 1 answers

2
Andrew Guy On BEST ANSWER

Two things going on here.

Firstly, the root logger is instantiated with a level of WARNING, which means that no messages with a level lower than WARNING will be processed. You can set the level using Logger.setLevel(level), where levels are defined here - https://docs.python.org/2/library/logging.html#levels.

As suggested in comments, the log level can also be set with:

basicConfig(level='INFO', ...)

Secondly, when you write to the StringIO object, the position in the stream is set at the end of the current stream. You need to rewind the StringIO object to then be able to read from it.

console.stream.seek(0)
console.stream.read()

Even simpler, just call:

console.stream.getvalue()

Full code:

from sys import stdout, stderr
from cStringIO import StringIO
from logging import getLogger, basicConfig, StreamHandler

basicConfig(format='%(asctime)s %(name)-12s %(levelname)-8s %(message)s',
            datefmt='%m-%d %H:%M')

log = getLogger(__name__)
log.setLevel("INFO")
sio = StringIO()
console = StreamHandler(sio)

log.addHandler(console)
log.addHandler(StreamHandler(stdout))

log.info('Jackdaws love my big sphinx of quartz.')
console.stream.seek(0)
print 'console.stream.read() = {!r}'.format(console.stream.read())