Is it possible to print different levels to different streams usingthe logging module?

D

Dotan Barak

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).


Thanks in advanced
Dotan Barak
 
P

Peter Otten

Dotan said:
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
 
V

Vinay Sajip

Hi.

I would like to use theloggingmodule 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 theloggingmodule)..

Thanks in advanced
Dotan Barak

Peter's answer is good, and you can also look at a slightly different
take on it (for a slightly different requirement - printing INFO only
to stdout, and everything else to stderr).

http://stackoverflow.com/questions/...mhandler-and-standard-streams/1383365#1383365

Regards,

Vinay Sajip
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

Forum statistics

Threads
473,768
Messages
2,569,574
Members
45,048
Latest member
verona

Latest Threads

Top