Loguru:优雅的Python程序日志
2020-07-17 本文已影响0人
SeanCheney
![](https://img.haomeiwen.com/i7178691/ab2f8f926529a5cf.png)
习惯了使用Python自带的
logging
模块记录日志,但是总觉得不够优雅。
Loguru解决了这个问题。guru是印度语中大师的意思,直译就是“日志大师”。
![](https://img.haomeiwen.com/i7178691/0bd1505b39519ccf.png)
![](https://img.haomeiwen.com/i7178691/a3000108893d6c99.gif)
使用pip安装
pip install loguru
开箱即用
不同的日志等级,输出效果也不一样(等级由低到高是DEBUG
、INFO
、WARNING
、ERROR
、CRITICAL
)
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!")
![](https://img.haomeiwen.com/i7178691/3137a25d3fa43b02.png)
统一的add()
函数
add()
函数用于注册“沉量”sink
,用于管理日志消息。
logger.add(sink='log.txt', format="{time} {level} {message}", filter="my_module", level="INFO")
将上面两个功能合起来,就能实现最基本的日志功能了。
from loguru import logger
logger.add(sink='log.log', format="{time} - {level} - {message}", level="INFO")
logger.info("That's it, beautiful and simple logging!")
可以用rotation
、retention
、compression
进行日志窗口、更新、压缩管理。
logger.add("file_1.log", rotation="500 MB") # 日志文件的窗口大小是500M
logger.add("file_2.log", rotation="12:00") # 每天中午12点创建新日志文件
logger.add("file_3.log", rotation="1 week") # 自动更新旧文件
logger.add("file_X.log", retention="10 days") # 清理旧文件
logger.add("file_Y.log", compression="zip") # 压缩文件
loguru支持f-string
:
logger.info("If you're using Python {}, prefer {feature} of course!", 3.6, feature="f-strings")
Loguru支持在主进程和线程中捕获异常,使用@logger.catch
from loguru import logger
logger.add(sink='log.log', format="{time} - {level} - {message}", level="INFO")
@logger.catch
def my_function(x, y, z):
return 1 / (x + y + z)
res = my_function(0,0,0)
print(res)
修改日志文字的颜色
logger.add(sys.stdout, colorize=True, format="<green>{time}</green> <level>{message}</level>")
使用enqueue
,可以保证多线程安全、多进程安全
logger.add("somefile.log", enqueue=True)
详细的异常回溯
使用backtrace
、diagnose
from loguru import logger
logger.add("output.log", backtrace=True, diagnose=True) # 设置为'False'可以保证生产中不泄露信息
def func(a, b):
return a / b
def nested(c):
try:
func(5, c)
except ZeroDivisionError:
logger.exception("What?!")
nested(0)
修改时间格式
logger.add("file.log", format="{time:YYYY-MM-DD at HH:mm:ss} | {level} | {message}")
参考:
https://github.com/Delgan/loguru
https://loguru.readthedocs.io/en/stable/overview.html