在编写和调试Python代码时,日志记录是一个常见的需求。通常,我们会选择使用Python内置的标准库logging来记录日志,但是配置起来相对繁琐。
为了提高编码效率,本文介绍了一个近期发现的宝藏第三方日志库Loguru,该库名字来源于印度语,意为日志大师。
01
引言
我们先来对比一下,以说明Loguru的优雅之处。 使用Python内置的logging库,示例代码如下:
<code>import logging logging.basicConfig(level=logging.DEBUG, format='%(asctime)s - %(levelname)s: %(message)s') logging.debug("This is logging DEBUG test ") logging.info("This is logging INFO test ") logging.warning("This is logging WARN test ") logging.error("This is logging ERROR test ")</code>
使用Loguru库,示例代码如下:
<code>from loguru import logger logger.debug("This is loguru DEBUG test") logger.info("This is loguru INFO test") logger.warning("This is loguru WARN test") logger.error("This is loguru ERROR test")</code>
使用Loguru输出日志后,终端会显示带颜色的日志,简洁又方便。
02
安装
直接使用pip进行安装,命令如下:
<code>pip install loguru</code>
默认输出到终端的使用方式:
<code>from loguru import logger logger.debug("msg msg msg!")</code>
输出到文件的使用方式:
<code>from loguru import logger logger.add("file_name.log") logger.debug("msg msg msg!")</code>
03
特性
参考官方GitHub,Loguru库提供了丰富的特性,下面介绍其中几个重要的特性:
1) 开箱即用
Loguru库的设计初衷是为了提供一个logger,使得日志记录更加方便。只需简单调用即可:
<code>from loguru import logger logger.debug("That's it, beautiful and simple logging!")</code>
2) 无需初始化,导入函数即可使用
Loguru库支持自定义输出样式、过滤输出信息和设置日志级别,只需调用add()函数:
<code>from loguru import logger logger.add("info.log", format="{time} {level} {message}", filter="", level="INFO") logger.debug("This is a debug msg") logger.info("This is a info msg")</code>
3) 更容易的文件日志记录与转存/保留/压缩方式
通过简单的配置,可以实现更人性化的日志保存,例如自动删除老日志或自动压缩保存的日志:
<code>logger.add("file_1.log", rotation="500 MB") logger.add("file_2.log", rotation="12:00") logger.add("file_3.log", rotation="1 week") logger.add("file_4.log", retention="10 days") logger.add("file_5.log", compression="zip")</code>
4) 更优雅的字符串格式化输出
Loguru库的字符串格式化功能更强大,支持{}进行替换,类似于str.format():
<code>logger.info("If you're using Python {}, prefer {feature} of course!", 3.6, feature="f-strings")</code>
5) 可以在线程或主线程中捕获异常
通过@logger.catch装饰器,可以确保发生异常时保存错误信息:
<code>@logger.catch def my_function(x, y, z): return 1 / (x + y + z) res = my_function(0,0,0) print(res)</code>
这个功能实在太赞了!
04
总结
本文对Loguru库的主要特性进行了简要概述,如需了解更详细的特性说明,请参考官方代码仓库。
暂无评论内容