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

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

    Just for your convenience adding everything together with the formatter in one package:

    # shared formatter, but you can use separate ones:
    FORMAT = '%(asctime)s - %(name)s - %(levelname)s - %(threadName)s - %(message)s'
    formatter = logging.Formatter(FORMAT)
    
    # single app logger:
    log = logging.getLogger(__name__)
    log.setLevel(logging.INFO)
    
    # 2 handlers for the same logger:
    h1 = logging.StreamHandler(sys.stdout)
    h1.setLevel(logging.DEBUG)
    # filter out everything that is above INFO level (WARN, ERROR, ...)
    h1.addFilter(lambda record: record.levelno <= logging.INFO)
    h1.setFormatter(formatter)
    log.addHandler(h1)
    
    h2 = logging.StreamHandler(sys.stderr)
    # take only warnings and error logs
    h2.setLevel(logging.WARNING)
    h2.setFormatter(formatter)
    log.addHandler(h2)
    
    # profit:
    log.info(...)
    log.debug(...)
    

    My use case was to redirect stdout to a datafile while seeing errors on the screen during processing.

提交回复
热议问题