• 欢迎访问搞代码网站,推荐使用最新版火狐浏览器和Chrome浏览器访问本网站!
  • 如果您觉得本站非常有看点,那么赶紧使用Ctrl+D 收藏搞代码吧

Python 第三方日志框架loguru使用

python 搞代码 4年前 (2022-01-09) 14次浏览 已收录 0个评论
文章目录[隐藏]

解决中文乱码问题

项目地址 github: https://github.com/Delgan/loguru
文档:https://loguru.readthedocs.io/en/stable/index.html

安装

pip install loguru

1、输出日志

from loguru import logger
logger.debug("这是一条debug日志")

终端执行后出现带颜色的日志,挺酷的

2、输出到文件

from loguru import logger

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

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

目录下多出一个日志文件 :file_2019-03-14_19-53-25_661314.log

3、日志规则

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

from loguru import logger

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

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

输出

2019-03-14T20:01:25.392454+0800 INFO 这是一条info日志

4、日志文件

文件管理方式

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格式

5、其他参数

logger.add("somefile.log", en<strong style="color:transparent">本文来源gao@daima#com搞(%代@#码@网&</strong>queue=True)  # 异步写入

logger.add("somefile.log", serialize=True)  # 序列化为json

6、时间格式化

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/

7、在工程中创建多个文件处理器对象并解决中文乱码问题

# coding=utf-8
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.log')
err_log_file_path = os.path.join(BASE_DIR, 'Log/err.log')

logger.add(sys.stderr, format="{time} {level} {message}", filter="my_module", level="INFO")
# logger.add(s)
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("严重错误")

以上就是Python 第三方日志框架loguru使用的详细内容,更多关于Python 日志框架loguru的资料请关注搞代码其它相关文章!


搞代码网(gaodaima.com)提供的所有资源部分来自互联网,如果有侵犯您的版权或其他权益,请说明详细缘由并提供版权或权益证明然后发送到邮箱[email protected],我们会在看到邮件的第一时间内为您处理,或直接联系QQ:872152909。本网站采用BY-NC-SA协议进行授权
转载请注明原文链接:Python 第三方日志框架loguru使用

喜欢 (0)
[搞代码]
分享 (0)
发表我的评论
取消评论

表情 贴图 加粗 删除线 居中 斜体 签到

Hi,您需要填写昵称和邮箱!

  • 昵称 (必填)
  • 邮箱 (必填)
  • 网址