python打印程序的运行log模块有:
python内置 log记录库有logging模块、还有logzero(star 1k)、logbook(1.4k)、loguru(11.9k)
以下是对应官方文档:
logzero:https://logzero.readthedocs.io/en/latest/
logbook:https://github.com/getlogbook/logbook
loguru: https://loguru.readthedocs.io/en/stable/index.html
本文使用loguru模块
安装:pip install loguru
输出等级 DEBUG、INFO、WARNING、ERROR、CRITICAL
from loguru import logger
logger.debug("That's it, beautiful and simple logging!")
logger.info("That's it, beautiful and simple logging!")
logger.warning("That's it, beautiful and simple logging!")
logger.error("That's it, beautiful and simple logging!")
logger.critical("That's it, beautiful and simple logging!")
2022-11-24 14:27:47.439 | DEBUG | __main__:<module>:9 - That's it, beautiful and simple logging!
2022-11-24 14:27:47.439 | INFO | __main__:<module>:10 - That's it, beautiful and simple logging!
2022-11-24 14:27:47.439 | WARNING | __main__:<module>:11 - That's it, beautiful and simple logging!
2022-11-24 14:27:47.439 | ERROR | __main__:<module>:12 - That's it, beautiful and simple logging!
2022-11-24 14:27:47.439 | CRITICAL | __main__:<module>:13 - That's it, beautiful and simple logging!
logger.info(“If you’re using Python {}, prefer {feature} of course!”, 3.6, feature=“f-strings”)
将日志输出到了log.txt文件中,并格式化输出。
logger.add(sink=‘log.txt’, format=“{time} {level} {message}”, filter=“my_module”, level=“INFO”)
logger.add(“file.log”, format=“{time:YYYY-MM-DD at HH:mm:ss} | {level} | {message}”)
format:输出格式 2022-11-24 14:27:47.439 | INFO | main:<my_module>:12 - That’s it, beautiful and simple logging!
filter:过滤器
level:等级
使用参数对保存日志进行操作
logger.add(“file_1.log”, rotation=“500 MB”) #自动分割大文件
logger.add(“file_2.log”, rotation=“12:00”) #每天12:00自动更新
logger.add(“file_X.log”, retention=“10 days”) # 十天前的日志删除
logger.add(“file_Y.log”, compression=“zip”) # zip方式压缩
只保存文件,不在console中输出
logger.remove(handler_id = None) # 清除之前的设置