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

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

    right from the updated docs, it cover this case pretty well now.

    http://docs.python.org/howto/logging.html#logging-advanced-tutorial

    import sys # Add this.
    import logging
    
    # create logger
    logger = logging.getLogger('simple_example')
    logger.setLevel(logging.DEBUG)
    
    # create console handler and set level to debug
    ch = logging.StreamHandler( sys.__stdout__ ) # Add this
    ch.setLevel(logging.DEBUG)
    
    # create formatter
    formatter = logging.Formatter('%(asctime)s - %(name)s - %(levelname)s - %(message)s')
    
    # add formatter to ch
    ch.setFormatter(formatter)
    
    # add ch to logger
    logger.addHandler(ch)
    
    # 'application' code
    logger.debug('debug message')
    logger.info('info message')
    logger.warn('warn message')
    logger.error('error message')
    logger.critical('critical message')
    

    i've mentioned on comments the two changes required from the example to make the output go to stdout. you may also use filters to redirect depending on the level.

    more information to understand the changes is at http://docs.python.org/library/logging.handlers.html#module-logging.handlers

提交回复
热议问题