Is it possible to print different levels to different streams using the logging module?
Peter Otten
__peter__ at web.de
Sat Jan 16 10:40:53 EST 2010
Dotan Barak wrote:
> Hi.
>
> I would like to use the logging module and print the following levels to
> the mentioned streams:
>
> CRITICAL -> stderr
> ERROR -> stderr
> WARNING -> stderr
> INFO -> stdout
> DEBUG -> stdout
>
> I would like that every message will be printed only once, and for the
> stream that i choose.
> (I failed to find a "maximum level" for the handlers in the logging
> module).
I believe you have to write a custom filter:
import logging
import sys
from logging import NOTSET
class LevelFilter:
def __init__(self, min=NOTSET, max=NOTSET):
self.min = min
self.max = max
def filter(self, record):
if self.min != NOTSET and record.levelno < self.min:
return False
if self.max != NOTSET and record.levelno > self.max:
return False
return True
out = logging.StreamHandler(sys.stdout)
format_out = logging.Formatter("[via stdout] %(levelname)s: %(message)s")
out.setFormatter(format_out)
out.addFilter(LevelFilter(max=logging.INFO))
err = logging.StreamHandler(sys.stderr)
format_err = logging.Formatter("[via stderr] %(levelname)s: %(message)s")
err.setFormatter(format_err)
err.setLevel(logging.WARNING)
logger = logging.getLogger()
logger.setLevel(logging.INFO)
logger.addHandler(out)
logger.addHandler(err)
logger.info("foo")
logger.warn("bar")
Peter
More information about the Python-list
mailing list