logging 模块:记录日志

logging 模块可以用来记录日志:

In [1]:

  1. import logging

logging 的日志类型有以下几种:

  • logging.critical(msg)
  • logging.error(msg)
  • logging.warning(msg)
  • logging.info(msg)
  • logging.debug(msg) 级别排序为:CRITICAL > ERROR > WARNING > INFO > DEBUG > NOTSET

默认情况下,logging 的日志级别为 WARNING,只有不低于 WARNING 级别的日志才会显示在命令行。

In [2]:

  1. logging.critical('This is critical message')
  2. logging.error('This is error message')
  3. logging.warning('This is warning message')
  4.  
  5. # 不会显示
  6. logging.info('This is info message')
  7. logging.debug('This is debug message')
  1. CRITICAL:root:This is critical message
  2. ERROR:root:This is error message
  3. WARNING:root:This is warning message

可以这样修改默认的日志级别:

In [3]:

  1. logging.root.setLevel(level=logging.INFO)
  2.  
  3. logging.info('This is info message')
  1. INFO:root:This is info message

可以通过 logging.basicConfig() 函数来改变默认的日志显示方式:

In [4]:

  1. logging.basicConfig(format='%(asctime)s: %(levelname)s: %(message)s')
  2.  
  3. logger = logging.getLogger("this program")
  4.  
  5. logger.critical('This is critical message')
  1. CRITICAL:this program:This is critical message

原文: https://nbviewer.jupyter.org/github/lijin-THU/notes-python/blob/master/11-useful-tools/11.07-logging.ipynb