1、官方文档
链接:https://docs.python.org/zh-cn/3/howto/logging.html#
2、基本使用
import logging #加载模块
logging.basicConfig(level=logging.INFO) #设置logging输出级别
logger = logging.getLogger(__name__) #获取一个logger对象
logger.debug('This message should go to the log file')
logger.info('So should this')
logger.warning('And this, too')
logger.error('And non-ASCII stuff, too, like Øresund and Malmö')
当设置logging级别时,比它低级别的日志信息均将不会输出。默认级别是warning。
以上片段输出为:
INFO:__main__:So should this
WARNING:__main__:And this, too
ERROR:__main__:And non-ASCII stuff, too, like Øresund and Malmö
2.1 日志级别
日志级别从低到高(按严重性)分为:
2.2 设置日志格式
主要在于logging.basicConfig()
中的format
参数设置.
logging.basicConfig(format='%(asctime)s == %(levelname)s ====> %(message)s',
level=logging.DEBUG)
上式中的%(asctime)s会控制打印出日期信息,%(levelname)s则是日志级别,%(message)s就是日志的输出信息了。输出如下:
2022-04-02 15:33:30,134 == DEBUG ====> This message should go to the log file
2022-04-02 15:33:30,135 == INFO ====> So should this
2022-04-02 15:33:30,135 == WARNING ====> And this, too
2022-04-02 15:33:30,135 == ERROR ====> And non-ASCII stuff, too, like Øresund and Malmö
详细参数可见:https://docs.python.org/zh-cn/3/library/logging.html#logrecord-attributes
2.3 输出日志到文件
logging.basicConfig(filename='example.log',level=logging.DEBUG)
以上信息就会输入到example.log文件中。
2.4 同时输出日志到文件与屏幕
这里提供两种实现
import logging
import sys
logging.basicConfig(filename="log.txt", level=logging.INFO,
format='[%(asctime)s] %(message)s', datefmt='%H:%M:%S')
logging.getLogger().addHandler(logging.StreamHandler(sys.stdout))
以及
import logging
logger = logging.getLogger(__name__)
logger.setLevel(level=logging.INFO)
handler = logging.FileHandler("log.txt")
handler.setLevel(logging.INFO)
handler.setFormatter(logging.Formatter('%(asctime)s - %(name)s - %(levelname)s - %(message)s'))
console = logging.StreamHandler()
console.setLevel(logging.INFO)
#添加hanler
logger.addHandler(handler)
logger.addHandler(console)
最后输出到文件log.txt和屏幕,两种输出格式并不一致
//屏幕输出
Start print log
Something maybe fail.
Finish
//文件内容
2022-04-02 17:10:26,148 - __main__ - INFO - Start print log
2022-04-02 17:10:26,149 - __main__ - WARNING - Something maybe fail.
2022-04-02 17:10:26,149 - __main__ - INFO - Finish
推荐阅读:
记录python的logging模块使用及采坑 - Fred的文章 - 知乎
python 日志 logging模块(详细解析)