问题
Is it possible to have python logging messages which are INFO or DEBUG to go to stdout and WARNING or greater to go to stderr?
回答1:
This seems to do what I want:
#!/usr/bin/python
import sys
import logging
class InfoFilter(logging.Filter):
def filter(self, rec):
return rec.levelno in (logging.DEBUG, logging.INFO)
logger = logging.getLogger('__name__')
logger.setLevel(logging.DEBUG)
h1 = logging.StreamHandler(sys.stdout)
h1.setLevel(logging.DEBUG)
h1.addFilter(InfoFilter())
h2 = logging.StreamHandler()
h2.setLevel(logging.WARNING)
logger.addHandler(h1)
logger.addHandler(h2)
回答2:
I thought this would help: Handler.setLevel(lvl)
Sets the threshold for this handler to lvl. Logging messages which are less severe than lvl will be ignored. When a handler is created, the level is set to NOTSET (which causes all messages to be processed).
But now I see that it wouldn't do what you want (split INFO/DEBUG from WARNING/ERROR)
That being said, you could write a custom handler (a class extending logging.StreamHandler
for example), and overwrite the Handler.handle() method.
来源:https://stackoverflow.com/questions/16061641/python-logging-split-between-stdout-and-stderr