Skills2026年4月14日·1 分钟阅读

Loguru — Python Logging Made Stupidly Simple

Loguru replaces Python logging boilerplate with a single import. No handlers, no formatters, no config files — just logger.info(). It adds colorized output, structured context, file rotation, and exception diagnosis out of the box.

Agent 就绪

Agent 可直接安装

这个资产可安装;Agent 先选择当前运行时、检查安装计划,再运行匹配命令。

Native · 98/100策略:允许
Agent 入口
任意 MCP/CLI Agent
类型
Skill
安装
Single
信任
信任等级:Established
入口
step-1.md
直接安装命令
npx -y tokrepo@latest install 6922366e-37b5-11f1-9bc6-00163e2b0d79 --target codex

先 dry-run 确认安装计划,再运行此命令。

TL;DR
Loguru replaces Python stdlib logging with one import: colorized output, rotation, and exception tracing included.
§01

What it is

Loguru is a Python logging library that replaces the standard library's logging module with a simpler API. One import gives you colorized terminal output, structured context binding, file rotation, and enhanced exception diagnosis. No handlers, no formatters, no configuration files.

Loguru is for Python developers who find the stdlib logging module tedious to set up. If you have ever written logging.basicConfig(level=logging.DEBUG, format='%(asctime)s...') and wished for something simpler, Loguru is the answer.

§02

How it saves time or tokens

Python's stdlib logging requires creating loggers, handlers, formatters, and wiring them together. A basic setup that logs to both console and file with rotation takes 10-15 lines. Loguru does the same in 2 lines.

For debugging, Loguru's logger.exception() captures the full traceback with local variable values at each frame. Instead of reading a bare traceback and guessing variable state, you see exactly what each variable contained when the error occurred.

§03

How to use

  1. Install Loguru:
pip install loguru
  1. Start logging immediately:
from loguru import logger

logger.info('Application started')
logger.warning('Disk usage at 85%')
logger.error('Failed to connect to database')
  1. Add file logging with rotation:
logger.add('app.log', rotation='10 MB', retention='7 days', compression='gz')
§04

Example

Structured logging with context and exception diagnosis:

from loguru import logger
import sys

# Configure structured JSON output for production
logger.remove()  # Remove default handler
logger.add(sys.stderr, format='{time} | {level} | {message}')
logger.add('app.log', serialize=True)  # JSON lines

# Bind context to all subsequent log calls
user_logger = logger.bind(user_id='u_12345', request_id='req_abc')
user_logger.info('Processing payment')

# Exception diagnosis with variable inspection
try:
    amount = 99.99
    currency = 'USD'
    result = process_charge(amount, currency)
except Exception:
    logger.exception('Payment processing failed')
    # Loguru shows: amount=99.99, currency='USD' in the traceback
§05

Related on TokRepo

§06

Common pitfalls

  • Loguru replaces the default logger on import. If your project uses stdlib logging extensively with custom handlers, integrating Loguru requires care. Use logger.add(logging.Handler) to bridge the two systems.
  • The serialize=True option outputs JSON lines, which is useful for log aggregation (ELK, Loki) but makes terminal output unreadable. Use it only for file or remote sinks.
  • Loguru is thread-safe but not process-safe for file writes. In multiprocess applications, use the enqueue=True option to serialize writes through a queue.

常见问题

How does Loguru compare to Python stdlib logging?+

Loguru provides the same functionality with a simpler API. Stdlib logging requires creating loggers, handlers, and formatters separately. Loguru's single logger object handles everything. Loguru also adds features that stdlib lacks: colorized output, exception variable inspection, and built-in file rotation.

Can Loguru output structured JSON logs?+

Yes. Add a handler with serialize=True and Loguru outputs each log entry as a JSON line. The JSON includes timestamp, level, message, module, function, line number, and any bound context fields.

Does Loguru support log rotation?+

Yes. The logger.add() function accepts rotation (by size, time, or custom condition), retention (how long to keep old files), and compression (gz, zip) parameters. A single line replaces what requires RotatingFileHandler and TimedRotatingFileHandler in stdlib.

Can I use Loguru with Django or Flask?+

Yes. Configure Loguru as the primary logger and use InterceptHandler to redirect Django or Flask's internal logging through Loguru. This gives you consistent formatting and features across your application and framework logs.

Is Loguru suitable for production?+

Yes. Loguru is used in production Python applications. Its structured JSON output integrates with log aggregation platforms. The enqueue=True option ensures thread-safe writes, and retention policies prevent disk space issues.

引用来源 (3)

讨论

登录后参与讨论。
还没有评论,来写第一条吧。

相关资产