Loguru: An Elegant Python Logging Library – Features, Usage, and Integration
This article introduces Loguru, a powerful third‑party Python logging library, explains why it simplifies logging compared to the standard logging module, outlines its key features such as out‑of‑the‑box setup, asynchronous support, lazy evaluation, and structured logging, and provides practical code examples and integration tips for scripts, libraries, and Flask applications.
Loguru is a lightweight yet powerful third‑party logging library for Python that addresses many pain points of the built‑in logging module by offering a richer set of features and a more convenient API.
Why use Loguru? It provides simple, ready‑to‑use logging without the boilerplate required by logging , such as configuring handlers and formatters. It also supports advanced capabilities like asynchronous logging, lazy evaluation, and structured output.
Key features include:
Out‑of‑the‑box usage – just import and start logging.
No explicit initialization; functions are ready after import.
Easy file logging with rotation, retention, and compression options.
Elegant string formatting with colorized output.
Exception capture in threads and the main thread.
Customizable log levels and styles.
Thread‑ and process‑safe asynchronous logging.
Lazy evaluation via opt(lazy=True) to avoid unnecessary computation.
Full compatibility with the standard logging API.
JSON serialization for structured logs.
Contextual logging with bind() and filtering.
Patchable records and custom sinks.
Parsing utilities for log analysis.
Integration with notification services.
Flask integration example using an intercept handler.
Quick start example:
<code>from loguru import logger
logger.debug("That's it, beautiful and simple logging!")</code>Adding a sink with custom formatting:
<code>logger.add(sys.stderr, colorize=True, format="<green>{time}</green> <level>{message}</level>")
logger.add('logs/z_{time}.log', level='DEBUG', format='{time:YYYY-MM-DD :mm:ss} - {level} - {file} - {line} - {message}', rotation='10 MB')</code>Asynchronous logging can be enabled with the enqueue=True flag:
<code>logger.add('some_file.log', enqueue=True)</code>Lazy evaluation example:
<code>logger.opt(lazy=True).debug("If sink level <= DEBUG: {x}", x=lambda: expensive_function(2**64))</code>Creating a custom log level:
<code>new_level = logger.level("SNAKY", no=38, color="<yellow>", icon="🐍")
logger.log("SNAKY", "Here we go!")</code>Integration with Flask using an intercept handler:
<code>import logging, sys
from pathlib import Path
from flask import Flask
from loguru import logger
app = Flask(__name__)
class InterceptHandler(logging.Handler):
def emit(self, record):
logger_opt = logger.opt(depth=6, exception=record.exc_info)
logger_opt.log(record.levelname, record.getMessage())
def configure_logging(flask_app: Flask):
"""Configure logging for a Flask app"""
path = Path(flask_app.config['LOG_PATH'])
if not path.exists():
path.mkdir(parents=True)
log_name = Path(path, 'sips.log')
logging.basicConfig(handlers=[InterceptHandler(level='INFO')], level='INFO')
logger.configure(handlers=[{"sink": sys.stderr, "level": 'INFO'}])
logger.add(log_name, rotation='500 MB', encoding='utf-8', colorize=False, level='INFO')
</code>The add() function is central to Loguru; it accepts a sink argument that can be a file path, a file‑like object, a callable, or even a standard logging.Handler . The function returns an identifier that can later be used with remove() to stop logging to that sink.
<code>trace = logger.add('runtime.log')
logger.debug('this is a debug message')
logger.remove(trace)
logger.debug('this is another debug message')</code>Overall, Loguru offers a concise, feature‑rich alternative to the built‑in logging module, suitable for both quick scripts and large applications.
Python Programming Learning Circle
A global community of Chinese Python developers offering technical articles, columns, original video tutorials, and problem sets. Topics include web full‑stack development, web scraping, data analysis, natural language processing, image processing, machine learning, automated testing, DevOps automation, and big data.
How this landed with the community
Was this worth your time?
0 Comments
Thoughtful readers leave field notes, pushback, and hard-won operational detail here.