loguru Python 日志库

发布时间: 更新时间: 总字数:402 阅读时间:1m 作者: IP上海 分享 网址

loguru是Python开发的,更加优雅、简单的日志的输出工具。

安装

pip3 install loguru
pip install loguru -i https://mirrors.aliyun.com/pypi/simple/

使用

基本使用

from loguru import logger

logger.debug('debug hello world')
logger.debug('this is a debug message')
logger.info('this is another debug message')
logger.warning('this is another debug message')
logger.error('this is another debug message')
logger.info('this is another debug message')
logger.success('this is success message!')
logger.critical('this is critical message!')
  • 输出
2023-05-14 18:27:44.403 | DEBUG    | __main__:<module>:1 - debug hello world
...

输出到文件

from loguru import logger

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

日志轮转/压缩

from loguru import logger

# 每天 12:00 会创建一个新的文件
logger.add("file_{time}.log", rotation="12:00")

# 按周
logger.add('file_{time}.log', rotation='1 week')

# 按大小
logger.add("file_{time}.log", rotation="1 MB", compression="zip", enqueue=True)

logger.debug("That's it, beautiful and simple logging!")

支持 Backtrace

from loguru import logger

# Caution, may leak sensitive data in prod
logger.add("file_{time}.log", backtrace=True, diagnose=True)

def func(a, b):
    return a / b

def nested(c):
    try:
        func(5, c)
    except ZeroDivisionError:
        logger.exception("What?!")

nested(0)
  • 错误输出
2023-05-14 18:35:31.069 | ERROR    | __main__:nested:5 - What?!
Traceback (most recent call last):

  File "<stdin>", line 1, in <module>
> File "<stdin>", line 3, in nested
  File "<stdin>", line 2, in func

ZeroDivisionError: division by zero

邮件告警

使用 notifiers 模块当发生 ERROR 级别告警时,发送邮件提醒

import notifiers

from loguru import logger
from notifiers.logging import NotificationHandler

params = {
    "username": "from@gmail.com",
    "password": "iampassword",
    "to": "to@gmail.com"
}

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

# 发生 Error 日志时,发邮件进行警报
handler = NotificationHandler("gmail", defaults=params)
logger.add(handler, level="ERROR")

自定义格式

from loguru import logger

# 配置重定向路径&格式
logger.add('file_{time}.log',format='{level} {time} {message}')

logger.debug('this is a redirect to file message')

extra

from loguru import logger

logger.add("file.log", format="{extra[ip]} {extra[user]} {message}")

context_logger = logger.bind(ip="192.168.0.1", user="someone")
context_logger.info("Contextualize your logger easily")
context_logger.bind(user="someone_else").info("Inline binding of extra attribute")
context_logger.info("Use kwargs to add context during formatting: {user}", user="anybody")
Home Archives Categories Tags Statistics
本文总阅读量 次 本站总访问量 次 本站总访客数