So I'm putting .info
in one StringIO and .error
in another StringIO.
How do I stop them from both being put into both?
Prelude:
from __future__ import print_function
import logging
from io import IOBase
from sys import stdout
from platform import python_version_tuple
if python_version_tuple()[0] == '3':
from IO import StringIO
else:
try:
from cStringIO import StringIO
except ImportError:
from StringIO import StringIO
Code:
# Some other file, like __init__.py
logging.basicConfig(
format='%(asctime)s %(name)-12s %(levelname)-8s %(message)s', level='INFO')
handler = logging.root.handlers.pop()
assert logging.root.handlers == [], "root logging handlers aren't empty"
handler.stream.close()
handler.stream = stdout
logging.root.addHandler(handler)
# Some other file, like __init__.py
log = logging.getLogger(__name__)
stderr_stream = logging.StreamHandler(StringIO())
log.addHandler(stderr_stream)
log.setLevel(logging.ERROR)
print('log.level =', {logging.INFO: 'INFO',
logging.ERROR: 'ERROR'}[log.level])
stdout_stream = logging.StreamHandler(StringIO())
log.addHandler(stdout_stream)
log.setLevel(logging.INFO)
print('log.level =', {logging.INFO: 'INFO',
logging.ERROR: 'ERROR'}[log.level])
log.info('hello')
log.error('world')
print('stderr_stream =', stderr_stream.stream.getvalue())
print('stdout_stream =', stdout_stream.stream.getvalue())
http://ideone.com/Nj6Asz output:
log.level = ERROR
log.level = INFO
2016-12-23 09:03:27,761 __main__ INFO hello
2016-12-23 09:03:27,761 __main__ ERROR world
stderr_stream = hello
world
stdout_stream = hello
world
This can be achieved by using a Filter. Since the filter function is an arbitrary boolean function (which returns zero/nonzero for some reason) you can have it filtering the level for a minimum AND a maximum:
...