Master Loguru: Simplify Python Logging with Powerful Features

This guide introduces Loguru, a modern Python logging library that replaces the standard logging module with a concise API, automatic coloring, thread‑safe operation, file rotation, JSON output, and extensive configuration options, providing clear examples, advanced settings, testing integration, and best‑practice project structures.

Test Development Learning Exchange
Test Development Learning Exchange
Test Development Learning Exchange
Master Loguru: Simplify Python Logging with Powerful Features

What is Loguru?

Loguru is a modern, concise, and powerful Python logging library designed to replace the standard logging module. It simplifies logging usage and offers many out‑of‑the‑box features such as automatic colored terminal output, multi‑thread/async safety, file writing with rotation and compression, a more intuitive API, and support for structured (JSON) logs.

Why Choose Loguru?

The built‑in logging module is feature‑rich but cumbersome to configure, often resulting in verbose code. Loguru aims to provide the same capabilities with far less boilerplate, making logging easier to read and maintain.

Installation

pip install loguru

Basic Usage

from loguru import logger
logger.debug("This is a debug message")
logger.info("This is an info message")
logger.warning("This is a warning message")
logger.error("This is an error message")

Typical output (default to standard output with colors):

2025-04-05 10:34:56.123 | DEBUG   | __main__:4 - This is a debug message
2025-04-05 10:34:56.124 | INFO    | __main__:5 - This is an info message
2025-04-05 10:34:56.124 | WARNING | __main__:6 - This is a warning message
2025-04-05 10:34:56.124 | ERROR   | __main__:7 - This is an error message

Advanced Configuration

1. Add File Output

logger.add("file.log", format="{time} {level} {message}", level="INFO")

This writes all logs of level INFO and above to file.log.

2. Log Rotation

# Each log file max 1 MB, keep up to 5 old files
logger.add("runtime_{time}.log", rotation="1 MB", retention="5 days", compression="zip")
# rotation can be "1 day", "10 MB", etc.
# retention defines how long logs are kept
# compression supports zip, gz, bz2, …

3. Custom Log Format

logger.add("custom_format.log", format="{time:YYYY-MM-DD HH:mm:ss} | {level} | {message}")
# Example output:
# 2025-04-05 10:34:56 | INFO | User login successful

4. Set Minimum Log Level

logger.add(sys.stderr, level="WARNING")  # only show WARNING and above
# Levels (low to high): TRACE < DEBUG < INFO < SUCCESS < WARNING < ERROR < CRITICAL

5. Remove Default Console Sink

logger.remove()  # remove all existing sinks
logger.add(sys.stderr, level="INFO")
logger.add("my_log_file.log")

6. Use a Function as Sink

def send_to_server(message):
    print("Sending log to remote server:", message)
logger.add(send_to_server, level="ERROR")

7. Filter Specific Modules or Content

logger.add("api.log", filter=lambda record: record["extra"].get("name") == "api")
# or shorthand
logger.add("db.log", filter="database")

8. Structured JSON Output

logger.add("json_output.log", serialize=True)
# Each line will be a JSON object, e.g.:
# {"elapsed":"0:00:00.123456","level":"INFO","message":"User login","time":"2025-04-05T10:34:56.123456Z"}

Testing with pytest

def test_log_message(caplog):
    with caplog.at_level("INFO"):
        logger.info("This is a test")
    assert "This is a test" in caplog.text

Integration with Other Tools

Loguru can be combined with frameworks such as FastAPI, Celery, or any custom monitoring solution by adding appropriate sinks or filters.

Recommended Project Structure

project/
│
├── logs/
│   └── app.log
│
├── utils/
│   └── logger.py   # encapsulates Loguru initialization
│
├── config/
│   └── logging_config.py
│
├── main.py
└── requirements.txt

Best‑Practice Wrapper (utils/logger.py)

from loguru import logger
import sys

def setup_logger(log_file="logs/app.log", level="DEBUG"):
    logger.remove()  # remove default sink
    logger.add(sys.stderr, level=level)  # console output
    logger.add(log_file, rotation="10 MB", retention="7 days", level="DEBUG", encoding="utf-8")
    return logger

logger = setup_logger()

Usage in other modules:

from utils.logger import logger
logger.info("Application started successfully")

Performance and Stability

Loguru supports multi‑threading and asyncio, performs reliably in large systems, and benefits from an active community with over 15 k GitHub stars.

Conclusion

Loguru offers a developer‑friendly, feature‑rich alternative to Python's built‑in logging, making it easier to produce readable, configurable, and structured logs for both development and production environments.

debuggingPerformanceTestingloggingLoguru
Test Development Learning Exchange
Written by

Test Development Learning Exchange

Test Development Learning Exchange

0 followers
Reader feedback

How this landed with the community

Sign in to like

Rate this article

Was this worth your time?

Sign in to rate
Discussion

0 Comments

Thoughtful readers leave field notes, pushback, and hard-won operational detail here.