Loguru:优雅的Python程序日志

时间:2022-07-22
本文章向大家介绍Loguru:优雅的Python程序日志,主要内容包括其使用实例、应用技巧、基本知识点总结和需要注意事项,具有一定的参考价值,需要的朋友可以参考一下。

习惯了使用Python自带的logging模块记录日志,但是总觉得不够优雅。 Loguru解决了这个问题。guru是印度语中大师的意思,直译就是“日志大师”。

使用pip安装

pip install loguru

开箱即用

不同的日志等级,输出效果也不一样(等级由低到高是DEBUGINFOWARNINGERRORCRITICAL

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!")

统一的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!")

可以用rotationretentioncompression进行日志窗口、更新、压缩管理。

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)

详细的异常回溯

使用backtracediagnose

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)

参考: https://github.com/Delgan/loguru https://loguru.readthedocs.io/en/stable/overview.html