Python logging split between stdout and stderr [duplicate]

怎甘沉沦 提交于 2019-12-29 03:17:30

问题


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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!