Python 记录日志简单好用,功能齐全(Loguru)

Loguru 一个能彻底解放你的日志记录器。

它即插即用,具备多种方式滚动日志、自动压缩日志文件、定时删除等功能。

除此之外,多线程安全、高亮日志、日志告警等功能也不在话下。

下面就给大家介绍一下这个强大工具的基本使用方法。

Loguru 安装方式很简单,打开终端输入即可完成安装。

pip install loguru

1. 在Loguru中,如果你需要输出 debug 日志到终端,可以这么做:

import traceback
from loguru import logger

logger.debug(traceback.format_exc())
logger.error(traceback.format_exc())

2. 如果你需要把日志输出到文件,只需要这样:

from loguru import logger

logger.add("email.log")
logger.info("邮件发送成功")
logger.error("邮件发送失败")

3. 使用 Loguru 我们可轻易地实现滚动日志--按时间滚动

比如按时间滚动,我们只需要在 logger.add 参数中添加一个 rotation 参数:

from loguru import logger
logger.add("file_2.log", rotation="12:00") # 每天12:00会创建一个新的文件
logger.debug("That's it, beautiful and simple logging!")

如图所示,过了设定的时间,则将原来的 file_2.log 重命名,并添加一个新的 file_2.log 文件。

除了按时间滚动日志外,Loguru 还可以按日志大小滚动:

from loguru import logger
logger.add("file_1.log", rotation="1 MB") # 滚动大日志文件
logger.debug("That's it, beautiful and simple logging!")

这样,一旦日志文件大小超过 1 MB 就会产生新的日志文件。

4. 压缩日志

如果你不想删除原有日志文件,Loguru 还支持将日志直接压缩:

from loguru import logger
logger.add("file_Y.log", compression="zip") # 压缩日志

5. 其他特性

(1)自定义颜色

Loguru 是支持自定义颜色的,如果你不喜欢它默认的颜色,可以这么改:

logger.add(sys.stdout, colorize=True, format="<green>{time}</green> <level>{message}</level>")

类似于HTML标签 <green></green> 标签中间的文字将会被标记为绿色。

(2)多线程安全

Loguru 默认情况下是线程安全的,但它不是多进程安全的。不过如果你需要多进程/异步记录日志,它也能支持,只需要添加一个 enqueue 参数:

logger.add("somefile.log", enqueue=True)

(3)邮件告警

Loguru 可以和强大的邮件通知模块 notifiers 库结合使用,以在程序意外失败时接收电子邮件,或发送许多其他类型的通知。

import notifiers

params = {
    "username": "you@gmail.com",
    "password": "abc123",
    "to": "dest@gmail.com"
}

# 初始化时发送一封邮件
notifier = notifiers.get_notifier("gmail")
notifier.notify(message="The application is running!", **params)

# 发生Error日志时,发邮件进行警报
from notifiers.logging import NotificationHandler

handler = NotificationHandler("gmail", defaults=params)
logger.add(handler, level="ERROR")

这样配置之后,每次产生 Error 日志,程序都会自动向你的邮箱发送告警,真的极其方便。

除了这些特性外,Loguru 还支持与 Python 原生的 Logging 模块兼容使用,你可以将原始的标准日志记录器记录的所有信息转移到Loguru中。

你还可以基于 Loguru 定制新的日志 Level,定制自己喜欢的结构化数据,详情可见 Loguru 的官方文档:https://github.com/Delgan/loguru

  • 1
    点赞
  • 10
    收藏
    觉得还不错? 一键收藏
  • 4
    评论
Python 中,可以使用 `logging` 模块记录日志。如果需要在多线程环境下记录日志,可以使用 `concurrent_log_handler` 模块来实现。 首先需要安装 `concurrent_log_handler` 模块: ``` pip install concurrent_log_handler ``` 然后,可以使用以下代码来记录日志: ```python import logging from concurrent_log_handler import ConcurrentRotatingFileHandler import threading # 创建日志记录器 logger = logging.getLogger(__name__) logger.setLevel(logging.DEBUG) # 创建文件处理器 handler = ConcurrentRotatingFileHandler(filename='example.log', mode='a', maxBytes=1024, backupCount=3) handler.setLevel(logging.DEBUG) formatter = logging.Formatter('%(asctime)s - %(levelname)s - %(message)s') handler.setFormatter(formatter) # 将处理器添加到记录器 logger.addHandler(handler) # 多线程记录日志 def worker(): logger.debug('Debug message from thread {0}'.format(threading.current_thread().name)) logger.info('Info message from thread {0}'.format(threading.current_thread().name)) logger.warning('Warning message from thread {0}'.format(threading.current_thread().name)) logger.error('Error message from thread {0}'.format(threading.current_thread().name)) logger.critical('Critical message from thread {0}'.format(threading.current_thread().name)) threads = [] for i in range(10): t = threading.Thread(target=worker) threads.append(t) t.start() for t in threads: t.join() ``` 上面的代码中,创建了一个 `ConcurrentRotatingFileHandler` 类实例化的文件处理器,它可以在多线程环境下安全地写入日志文件。然后,将处理器添加到日志记录器中,并使用多线程来记录日志

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 4
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值