logging模块
具有的功能:
1、日志格式的规范
2、操作的简化
3、日志的分级管理
# 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')
logging.debug("debug message") # 调试模式
logging.info("info message") # 基础信息模块
logging.warning("warning message") # 警告
logging.error("error message") # 错误
logging.critical("critical message") # 严重错误
Wed,13 May 2020 11:35:58 untitled0.py[line:10] DEBUG debug message
Wed,13 May 2020 11:35:58 untitled0.py[line:11] INFO info message
Wed,13 May 2020 11:35:58 untitled0.py[line:12] WARNING warning message
Wed,13 May 2020 11:35:58 untitled0.py[line:13] ERROR error message
Wed,13 May 2020 11:35:58 untitled0.py[line:14] CRITICAL critical message
# 第二种
# logger对象的形式来操作日志文件
import logging
# 创建一个logger对象
log = logging.getLogger()
# 创建一个文件管理操作符
fh = logging.FileHandler('logger.log',encoding = 'utf-8')
# 创建一个屏幕管理操作符
sh = logging.StreamHandler()
# log级别
log.setLevel(logging.DEBUG)
# 创建一个日志输出的格式
format1 = logging.Formatter('%(asctime)s - %(name)s - %(levelname)s - %(message)s')
# 文件管理操作符 绑定一个 格式
fh.setFormatter(format1)
# 屏幕管理操作符 绑定一个 格式
sh.setFormatter(format1)
# logger对象绑定文件管理操作符
log.addHandler(fh)
# logger对象绑定屏幕管理操作符
log.addHandler(sh)
log.debug("debug message 大弟子")
log.info("ingo message 中文")
DEBUG:root:debug message 大弟子
2020-05-13 16:17:52,116 - root - DEBUG - debug message 大弟子
2020-05-13 16:17:52,116 - root - DEBUG - debug message 大弟子
2020-05-13 16:17:52,116 - root - DEBUG - debug message 大弟子
debug message 大弟子
INFO:root:ingo message 中文
2020-05-13 16:17:52,128 - root - INFO - ingo message 中文
2020-05-13 16:17:52,128 - root - INFO - ingo message 中文
2020-05-13 16:17:52,128 - root - INFO - ingo message 中文
ingo message 中文