Python 中更优雅的日志记录方案——loguru

python日志记录方案

在 Python 中,一般情况下我们可能直接用自带的 logging 模块来记录日志,包括我之前的时候也是一样。在使用时我们需要配置一些 Handler、Formatter 来进行一些处理,比如把日志输出到不同的位置,或者设置一个不同的输出格式,或者设置日志分块和备份。但其实个人感觉 logging 用起来其实并不是那么好用,其实主要还是配置较为繁琐。

更优雅的方式

loguru

loguru不需要配置什么东西,直接引入一个 logger,然后调用其 debug 方法即可。在 loguru 里面有且仅有一个主要对象,那就是 logger,loguru 里面有且仅有一个 logger,而且它已经被提前配置了一些基础信息,比如比较友好的格式化、文本颜色信息等等。

安装

pip3 install loguru

使用

输出日志
1
2
from loguru import logger
logger.debug("这是一条debug日志")
输出到文件
1
2
3
4
5
6
from loguru import logger

logger.add("file_{time}.log")

logger.debug("这是一条debug日志")
logger.info("这是一条info日志")
日志规则

设置日志格式,过滤器,日志级别

1
2
3
4
5
6
from loguru import logger

logger.add("file.log", format="{time} {level} {message}", filter="", level="INFO")

logger.debug("这是一条debug日志")
logger.info("这是一条info日志")
日志文件

文件管理方式

1
2
3
4
5
6
7
logger.add("file_1.log", rotation="500 MB")    # 文件过大就会重新生成一个文件
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") # 保存zip格式
其他参数
1
2
3
logger.add("somefile.log", enqueue=True)  # 异步写入

logger.add("somefile.log", serialize=True) # 序列化为json
时间格式化
1
logger.add("file.log", format="{time:YYYY-MM-DD at HH:mm:ss} | {level} | {message}")

配合notifiers模块
github: https://github.com/notifiers/notifiers
文档:https://notifiers.readthedocs.io/en/latest/

在工程中创建多个文件处理器对象并解决中文乱码问题
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
import os
import sys
from loguru import logger

BASE_DIR = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))

log_file_path = os.path.join(BASE_DIR,'Log/my_first.log')
err_log_file_path = os.path.join(BASE_DIR,'Log/error.log')

logger.add(sys.stderr, format="{time} {level} {message}", filter="my_noudle", level="INFO")

logger.add(log_file_path, rotation="500 MB", encoding='utf-8') # Automatically rotate too big file
logger.add(err_log_file_path, rotation="500 MB", encoding='utf-8',
level='ERROR') # Automatically rotate too big file
logger.debug("That's it, beautiful and simple logging!")
logger.debug("中文日志可以不")
logger.error("严重错误")

Traceback 记录

在很多情况下,如果遇到运行错误,而我们在打印输出 log 的时候万一不小心没有配置好 Traceback 的输出,很有可能我们就没法追踪错误所在了。但用了 loguru 之后,我们用它提供的装饰器就可以直接进行 Traceback 的记录。用 loguru 可以非常方便地实现日志追踪

1
2
3
4
5
6
7
8
9
from loguru import logger

@logger.catch
def my_function(x, y, z):
# An error? It's caught anyway!
return 1 / (x + y + z)


my_function(0, 0, 0)

参考

Python 中更优雅的日志记录方案

loguru官方文档

Python 第三方日志框架loguru使用