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.
Installation agent prête
Cet actif peut être installé après choix du runtime, vérification du plan et exécution de la commande adaptée.
npx -y tokrepo@latest install 6922366e-37b5-11f1-9bc6-00163e2b0d79 --target codexÀ exécuter après confirmation du plan en dry-run.
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.
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.
How to use
- Install Loguru:
pip install loguru
- Start logging immediately:
from loguru import logger
logger.info('Application started')
logger.warning('Disk usage at 85%')
logger.error('Failed to connect to database')
- Add file logging with rotation:
logger.add('app.log', rotation='10 MB', retention='7 days', compression='gz')
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
Related on TokRepo
- Coding AI tools -- Python developer tools
- Monitoring tools -- logging and observability
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=Trueoption 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=Trueoption to serialize writes through a queue.
Questions fréquentes
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.
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.
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.
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.
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.
Sources citées (3)
- Loguru GitHub— Loguru Python logging library
- Loguru Documentation— Logger configuration and sinks
- Python Logging Documentation— Python logging module and handlers
En lien sur TokRepo
Fil de discussion
Actifs similaires
Dash — Data Apps and Dashboards in Pure Python
Dash by Plotly lets you build interactive analytical web applications entirely in Python, with no JavaScript required. It powers data dashboards across finance, biotech, and engineering.
Logrus — Structured Logging Library for Go
A structured logger for Go with pluggable hooks, formatters, and level-based filtering. Drop-in replacement for the standard library logger with JSON and text output built in.
winston — Versatile Logging Library for Node.js
winston is the most popular logging library for Node.js, offering multiple transports, structured JSON output, and configurable log levels for production applications.
SQLGlot — SQL Parser, Transpiler & Optimizer in Pure Python
SQLGlot is a no-dependency Python library that parses, transpiles, and optimizes SQL across 20+ dialects. Convert queries between Snowflake, BigQuery, DuckDB, Spark, Postgres, and more without touching the database.