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

后端 未结 7 996
悲哀的现实
悲哀的现实 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:05

    I had the same problem and wrote a custom logging handler called SplitStreamHandler:

    import sys
    import logging
    
    class SplitStreamHandler(logging.Handler):
        def __init__(self):
            logging.Handler.__init__(self)
    
        def emit(self, record):
            # mostly copy-paste from logging.StreamHandler
            try:
                msg = self.format(record)
                if record.levelno < logging.WARNING:
                    stream = sys.stdout
                else:
                    stream = sys.stderr
                fs = "%s\n"
    
                try:
                    if (isinstance(msg, unicode) and
                        getattr(stream, 'encoding', None)):
                        ufs = fs.decode(stream.encoding)
                        try:
                            stream.write(ufs % msg)
                        except UnicodeEncodeError:
                            stream.write((ufs % msg).encode(stream.encoding))
                    else:
                        stream.write(fs % msg)
                except UnicodeError:
                    stream.write(fs % msg.encode("UTF-8"))
    
                stream.flush()
            except (KeyboardInterrupt, SystemExit):
                raise
            except:
                self.handleError(record)
    

提交回复
热议问题