在程序中使用logging日志,方便记录并定位问题。
一、日志处理模块导入
import logging
二、日志等级
- NOSET,0,等于没写,废话
- DEBUG ,10,调试,一些额外信息、备注等,往往和主体功能无关
- INFO,20,主体功能的信息,比如记录做了什么
- WARNING,30,警告,可能有错误
- ERROR,40,错误
- CRITICAL,50,及其严重
一般来说,直接使用logging会有以下问题:1、日志只能在运行过程中,从控制台查看;2、等级为INFO及以下的日志信息没有被打印;3、无法查看运行时间、位置等信息。因此,建议不要使用logging.info()等操作。
三、日志定制
1、获取日志收集器logger
2、设置收集器级别
收集器级别设置后,只有级别等于或高于设置的级别才会被收集器捕捉到,比如设置为‘INFO’,NOSET和DEBUG级别的就不会被收集器收集。
3、准备日志处理器handler
有两种日志处理器,一种是控制台输出处理器StreamHandler,收集的日志直接在控制台输出,另一种是文件处理器FileHandler,收集的日志会存储到指定的文件里,方便随时查阅。
4、日志处理器设置级别
5、设置日志格式
比较常用的日志格式如下:
- asctime,%(asctime)s,表示运行时间,默认形式为 '2021-01-06 15:09:45,896'
- filename,%(filename)s,表示文件名,比如test.py
- name,%(name)s,表示收集器名称,用户自定义的
- levelname,%(levelname)s,表示日志的记录级别,比如‘INFO’、‘ERROR’等
- lineno,%(lineno)d,表示日志记录调用所在的源行号
- message,%(message)s,表示日志信息
6、将日志处理器添加至日志收集器