loguru保存到zip压缩文件
使用如下代码保存日志文件到zip压缩文件中:
from loguru import logger
import sys
logger.remove()
logger.add("my_cal_record", filter=lambda record: "DEBUG" in record['level'].name, level="DEBUG",
format="{time:YYYY-MM-DD HH:mm:ss.SSS} {level} {message}", enqueue=True, mode='w', compression="zip")
logger.add(sys.stderr, level="DEBUG")
# 这里我们执行一个循环操作
for i in range(20):
logger.debug(i)
可以看到本地生成了日志文件my_cal_record.zip
,解压并以文本格式打开my_cal_record
文件可以看到如下内容:
2022-12-11 09:15:14.273 DEBUG 0
2022-12-11 09:15:14.273 DEBUG 1
......
loguru解析zip文件
使用如下代码解析:
from loguru import logger
import dateutil
from dateutil.parser import parser
from zipfile import ZipFile
import io
pattern = r"(?P<time>\d{4}-\d{2}-\d{2}\s\d{2}:\d{2}:\d{2}.\d{3}) (?P<level>DEBUG) (?P<message>.*)"
caster_dict = dict(time=dateutil.parser.parse, level=str)
record_list = []
zf = ZipFile('my_cal_record.zip')
for filename in zf.namelist():
with zf.open(filename, 'r') as f:
for log_groups in logger.parse(io.TextIOWrapper(f, newline=None), pattern, cast=caster_dict):
record_list.append(eval(log_groups['message']))
print(record_list)
得到结果:
[0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19]
更多loguru的用法请参考:https://betterstack.com/community/guides/logging/loguru/