Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Python logging to stdout and StringIO

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.'
like image 417
A T Avatar asked Nov 27 '25 21:11

A T


1 Answers

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())
like image 53
Andrew Guy Avatar answered Nov 30 '25 12:11

Andrew Guy



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!