logging
模块可以用来记录日志:
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
级别的日志才会显示在命令行。
logging.critical('This is critical message')
logging.error('This is error message')
logging.warning('This is warning message')
# 不会显示
logging.info('This is info message')
logging.debug('This is debug message')
CRITICAL:root:This is critical message
ERROR:root:This is error message
WARNING:root:This is warning message
可以这样修改默认的日志级别:
logging.root.setLevel(level=logging.INFO)
logging.info('This is info message')
INFO:root:This is info message
可以通过 logging.basicConfig()
函数来改变默认的日志显示方式:
logging.basicConfig(format='%(asctime)s: %(levelname)s: %(message)s')
logger = logging.getLogger("this program")
logger.critical('This is critical message')
CRITICAL:this program:This is critical message