Loguru模块

与天地兮比寿,与日月兮齐光。这篇文章主要讲述Loguru模块相关的知识,希望能为你提供帮助。
一. 安装

pip3 install loguru

二. 基本使用我们直接通过导入loguru 封装好的logger 类的实例化对象,不需要手动创建 logger,直接进行调用不同级别的日志输出方法。我们先用一个示例感受下:
from loguru import loggerlogger.debug(\'This is debug information\') logger.info(\'This is info information\') logger.warning(\'This is warn information\') logger.error(\'This is error information\')

在 IDE 或终端运行时会发现,loguru 在输出的不同级别信息时,带上了不同的颜色,使得结果更加直观,其中也包含了时间、级别、模块名、行号以及日志信息。
loguru 中不同日志级别与日志记录方法对应关系 如下:
级别名称 严重度值 记录器法
TRACE 5 logger.trace()
DEBUG 10 logger.debug()
INFO 20 logger.info()
SUCCESS 25 logger.success()
WARNING 30 logger.warning()
ERROR 40 logger.error()
CRITICAL 50 logger.critical()
三. loguru 配置日志文件logger 默认采用 sys.stderr 标准错误输出将日志输出到控制台中,假如想要将日志同时输出到其他的位置,比如日志文件,此时我们只需要使用一行代码即可实现。
【Loguru模块】例如,将日志信息输出到 2021-3-28.log 文件中,可以这么写:
from loguru import loggerlogger.add("E:/pythonCode/MOC/log_2021-3-28.log",rotation="500MB", encoding="utf-8", enqueue=True, retention="10 days")logger.info(\'This is info information\')

如上,loguru直接通过 add() 方法,完成了日志文件的配置。
四. 日志内容的字符串格式化loguru 在输出 日志的时候,还提供了非常灵活的字符串格式化输出日志的功能,如下:
import platform from loguru import loggerrounded_value = https://www.songbingjia.com/android/round(0.345, 2)trace= logger.add(/'2021-3-28.log\')logger.info(\'If you are using Python {version}, prefer {feature} of course!\', version=platform.python_version(), feature=\'f-strings\')# 执行上述代码,输出结果为 2021-03-28 13:43:26.232 | INFO| __main__:< module> :9 - If you are using Python 3.7.6, prefer f-strings of course!

五. loguru日志常用参数配置解析 1. sink1. rotation
六. loguru 日志常用方式 1. 停止日志记录到文件中
from loguru import loggertrace= logger.add(\'2021-3-28.log\') logger.error(\'This is error information\')logger.remove(trace) logger.warning(\'This is warn information\')

2021-03-28 13:38:22.995 | ERROR| __main__:< module> :7 - This is error information2021-03-28 13:38:22.996 | WARNING| __main__:< module> :11 - This is warn information

2021-03-28 13:38:22.995 | ERROR| __main__:< module> :7 - This is error information

2. 只输出到文本,不在console输出
from loguru import logger # 清除之前的设置 logger.remove(handler_id=None) trace= logger.add(\'2021-3-28.log\')logger.error(\'This is error information\') logger.warning(\'This is warn information\')

3. filter 配置日志过滤规则
from loguru import loggerdef error_only(record): """ error 日志 判断 Args: record: Returns: 若日志级别为ERROR, 输出TRUE""" return record["level"].name == "ERROR"# ERROR以外级别日志被过滤掉 logger.add("2021-3-28.log", filter=error_only)logger.error(\'This is error information\') logger.warning(\'This is warn information\')

2021-03-28 17:01:33.267 | ERROR| __main__:< module> :11 - This is error information

4. format 配置日志记录格式化模板
from loguru import loggerdef format_log(): """Returns:""" trace = logger.add(\'2021-3-28.log\', format="{time:YYYY-MM-DD HH:mm:ss} {level} From {module}.{function} : {message}")logger.warning(\'This is warn information\')if __name__ == \'__main__\': format_log()

# 2021-3-28.log 2021-03-28 14:46:25 WARNING From 2021-3-28.format_log : This is warn information

Key Description
elapsed 从程序开始经过的时间差
exception 格式化异常(如果有),否则为\' None \'
extra 用户绑定的属性字典(参见bind())
file 进行日志记录调用的文件
function 进行日志记录调用的函数
level 用于记录消息的严重程度
line 源代码中的行号
message 记录的消息(尚未格式化)
module 进行日志记录调用的模块
name 进行日志记录调用的name
process 进行日志记录调用的进程名
thread 进行日志记录调用的线程名
time 发出日志调用时的可感知的本地时间
rom loguru import loggerdef format_log(): """Returns:""" trace = logger.add(\'2021-3-28.log\', format="{time:YYYY-MM-DD HH:mm:ss} {extra[ip]}{extra[username]} {level} From {module}.{function} : {message}")extra_logger = logger.bind(ip="192.168.0.1", username="张三") extra_logger.info(\'This is info information\') extra_logger.bind(username="李四").error("This is error information")extra_logger.warning(\'This is warn information\')if __name__ == \'__main__\': format_log()

2021-03-28 16:27:11 192.168.0.1张三 INFO From 2021-3-28.format_log : This is info information 2021-03-28 16:27:11 192.168.0.1李四 ERROR From 2021-3-28.format_log : This is error information 2021-03-28 16:27:11 192.168.0.1张三 WARNING From 2021-3-28.format_log : This is warn information

5. level 配置日志最低日志级别
from loguru import loggertrace = logger.add(\'2021-3-29.log\', level=\'ERROR\')

6. rotation 配置日志滚动记录的机制
from loguru import loggertrace = logger.add(\'2021-3-28.log\', rotation="200 MB")

from loguru import loggertrace = logger.add(\'2021-3-28.log\', rotation=\'06:00\')

from loguru import loggertrace = logger.add(\'2021-3-28.log\', rotation=\'2 week\')

7. retention 配置日志保留机制
from loguru import loggertrace = logger.add(\'2021-3-28.log\', retention=\'7 days\')

8. compression 配置日志压缩格式
from loguru import loggertrace = logger.add(\'2021-3-28.log\', compression=\'zip\')

9. serialize 日志序列化
from loguru import logger import platformrounded_value = https://www.songbingjia.com/android/round(0.345, 2)trace= logger.add(/'2021-3-28.log\', serialize=True)logger.info(\'If you are using Python {version}, prefer {feature} of course!\', version=platform.python_version(), feature=\'f-strings\')

{ "text": "2021-03-28 13:44:17.104 | INFO| __main__:< module> :9 - If you are using Python 3.7.6, prefer f-strings of course!\\n", "record": { "elapsed": { "repr": "0:00:00.010911", "seconds": 0.010911 }, "exception": null, "extra": { "version": "3.7.6", "feature": "f-strings" }, "file": { "name": "2021-3-28.py", "path": "F:/code/MOC/2021-3-28.py" }, "function": "< module> ", "level": { "icon": "\\u2139\\ufe0f", "name": "INFO", "no": 20 }, "line": 9, "message": "If you are using Python 3.7.6, prefer f-strings of course!", "module": "2021-3-28", "name": "__main__", "process": { "id": 22604, "name": "MainProcess" }, "thread": { "id": 25696, "name": "MainThread" }, "time": { "repr": "2021-03-28 13:44:17.104522+08:00", "timestamp": 1616910257.104522 } } }

10.Traceback 记录(异常追溯)
from loguru import loggertrace= logger.add(\'2021-3-28.log\')@logger.catch def index_error(custom_list: list):for index in range(len(custom_list)): index_value = https://www.songbingjia.com/android/custom_list[index] if custom_list[index] < 2 : custom_list.remove(index_value)print(index_value)if __name__ == /'__main__\': index_error([1,2,3])

2021-03-28 13:57:13.852 | ERROR| __main__:< module> :16 - An error has been caught in function \'< module> \', process \'MainProcess\' (7080), thread \'MainThread\' (32280): Traceback (most recent call last):> File "F:/code/MOC/2021-3-28.py", line 16, in < module> index_error([1,2,3]) └ < function index_error at 0x000001FEB84D0EE8> File "F:/code/MOC/2021-3-28.py", line 9, in index_error index_value = https://www.songbingjia.com/android/custom_list[index] │└ 2 └ [2, 3]IndexError: list index out of range

from loguru import loggertrace = logger.add(\'2021-3-28.log\')class Demo: @logger.catch def index_error(self, custom_list: list): for index in range(len(custom_list)): index_value = https://www.songbingjia.com/android/custom_list[index] if custom_list[index] < 2: custom_list.remove(index_value)@staticmethod @logger.catch def index_error_static(custom_list: list): for index in range(len(custom_list)): index_value = custom_list[index] if custom_list[index] < 2: custom_list.remove(index_value)if __name__ == /'__main__\': # Demo().index_error([1, 2, 3]) Demo.index_error_static([1, 2, 3])

2). 通过 logger.exception 方法也可以实现异常的捕获与记录:
from loguru import loggertrace = logger.add(\'2021-3-28.log\')def index_error(custom_list: list): for index in range(len(custom_list)): try: index_value = https://www.songbingjia.com/android/custom_list[index] except IndexError aserr: logger.exception(err) breakif custom_list[index] < 2: custom_list.remove(index_value)if __name__ == /'__main__\': index_error([1, 2, 3])


    推荐阅读