How can INFO and DEBUG logging message be sent to stdout and higher level message to stderr

后端 未结 7 1000
悲哀的现实
悲哀的现实 2020-12-10 00:32

Is there an easy way with python\'s logging module to send messages with a DEBUG or INFO level and the one with a higher level to different streams?

Is it a good ide

7条回答
  •  佛祖请我去吃肉
    2020-12-10 01:04

    #!/usr/bin/env python3
    # -*- coding: utf-8 -*-
    import logging
    import sys
    
    class LessThenFilter(logging.Filter):
        def __init__(self, level):
            self._level = level
            logging.Filter.__init__(self)
    
        def filter(self, rec):
            return rec.levelno < self._level
    
    log = logging.getLogger()
    log.setLevel(logging.NOTSET)
    
    sh_out = logging.StreamHandler(stream=sys.stdout)
    sh_out.setLevel(logging.DEBUG)
    sh_out.setFormatter(logging.Formatter('%(levelname)s: %(message)s'))
    sh_out.addFilter(LessThenFilter(logging.WARNING))
    log.addHandler(sh_out)
    
    sh_err = logging.StreamHandler(stream=sys.stderr)
    sh_err.setLevel(logging.WARNING)
    sh_err.setFormatter(logging.Formatter('%(levelname)s: %(message)s'))
    log.addHandler(sh_err)
    
    logging.critical('x')
    logging.error('x')
    logging.warning('x')
    logging.info('x')
    logging.debug('x')
    

提交回复
热议问题