1、日志的打印级别
日志级别大小关系为:CRITICAL > ERROR > WARNING > INFO > DEBUG > NOTSET,当然也可以自己定义日志级别。
默认情况下,logging将日志打印到屏幕,日志级别为WARNING 及以上;
import logging
logging.warning("This is a warning log")
logging.info("This is a info log")
logging.debug("This is a Debug log")
logging.error("This is a error log")
logging.critical("This is a critical log")
# WARNING:root:This is a warning log
# ERROR:root:This is a error log
# CRITICAL:root:This is a critical log
2、通过logging.basicConfig函数对日志的输出格式及方式做相关配置
import logging
logging.basicConfig(level=logging.DEBUG,
format='%(asctime)s %(filename)s[line:%(lineno)d] %(levelname)s %(message)s',
datefmt='%a, %d %b %Y %H:%M:%S',
filename='myapp.log',
filemode='w')
logging.warning("This is a warning log")
logging.info("This is a info log")
logging.debug("This is a Debug log")
logging.error("This is a error log")
logging.critical("This is a critical log")
"""
myapp.log
Mon, 06 Jan 2020 23:59:30 log.py[line:29] WARNING This is a warning log
Mon, 06 Jan 2020 23:59:30 log.py[line:30] INFO This is a info log
Mon, 06 Jan 2020 23:59:30 log.py[line:31] DEBUG This is a Debug log
Mon, 06 Jan 2020 23:59:30 log.py[line:32] ERROR This is a error log
Mon, 06 Jan 2020 23:59:30 log.py[line:33] CRITICAL This is a critical log
"""
3、在控制台打印warning级别以上的日志,在文件中输出全日志
import logging
logging.basicConfig(level=logging.DEBUG,
format='%(asctime)s %(filename)s[line:%(lineno)d] %(levelname)s %(message)s',
datefmt='%a, %d %b %Y %H:%M:%S',
filename='myapp.log',
filemode='w')
# 义一个StreamHandler,将INFO级别或更高的日志信息打印到标准错误,并将其添加到当前的日志处理对象#
console = logging.StreamHandler()
console.setLevel(logging.WARNING)
formatter = logging.Formatter('%(name)s: %(levelname)-1s %(message)s')
console.setFormatter(formatter)
logging.getLogger('').addHandler(console)
logging.warning("This is a warning log")
logging.info("This is a info log")
logging.debug("This is a Debug log")
logging.error("This is a error log")
logging.critical("This is a critical log")