How do I change the format of a Python log message on a per-logger basis?

后端 未结 2 396
情书的邮戳
情书的邮戳 2021-02-05 00:30

After reading the documentation on logging, I know I can use code like this to perform simple logging:

import logging

def main():
    logging.basicConfig(filena         


        
2条回答
  •  礼貌的吻别
    2021-02-05 00:56

    Try this

    import logging
    
    logger = logging.getLogger('simple_example')
    logger.setLevel(logging.DEBUG)
    # create file handler that logs debug and higher level messages
    fh = logging.FileHandler('spam.log')
    fh.setLevel(logging.DEBUG)
    # create console handler with a higher log level
    ch = logging.StreamHandler()
    ch.setLevel(logging.ERROR)
    # create formatter and add it to the handlers
    formatter = logging.Formatter(
        '%(asctime)s - %(name)s - %(levelname)s - %(message)s')
    ch.setFormatter(formatter)
    fh.setFormatter(formatter)
    # add the handlers to logger
    logger.addHandler(ch)
    logger.addHandler(fh)
    
    # 'application' code
    logger.debug('debug message')
    logger.info('info message')
    logger.warn('warn message')
    logger.error('error message')
    logger.critical('critical message')
    

    See http://docs.python.org/howto/logging-cookbook.html#multiple-handlers-and-formatters for more information

提交回复
热议问题