学习 python logging(1): 基本用法
简介
日志在编程中是十分重要,可以帮助我们跟踪事件、应用的运行情况、查问题、统计数据等。在记录日志时,通常表示某件事情的发生。
python 中 logging 模块提供记录的基础方法:
debug, info,warning, error, critical
这五个方法的严重等级依次增加,对应关系:
默认等级为 WARNING,只有高于你所指定的等级,才会被日志模块输出。
基本使用
- 直接打印
import logging logging.info(info log) logging.warning(warning log)
运行之后看到的是 WARNING:root:warning log ,因为默认等级是 WARNING, 所以 info log 是不会显示的。
- 将日志记录到文件中
import logging logging.basicConfig(filename=logging_example.log,level=logging.DEBUG) logging.debug(Write debug to file) logging.info(Write info to file) logging.warning(Write warning to file)
可以在日志文件中看到:
DEBUG:root:Write debug to file INFO:root:Write info to file WARNING:root:Write warning to file DEBUG:root:Write debug to file INFO:root:Write info to file WARNING:root:Write warning to file
参考:
