Python logging split between stdout and stderr [du

2019-02-02 02:00发布

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?

2条回答
Viruses.
2楼-- · 2019-02-02 02:45

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.

查看更多
叼着烟拽天下
3楼-- · 2019-02-02 02:51

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)
查看更多
登录 后发表回答