How to Use Loguru for Simpler Python Logging

How to Use Loguru for Simpler Python Logging

by Abdelhadi Dyouri Updated Reading time estimate 42m intermediate tools

In Python, logging is a vital programming practice that helps you track, understand, and debug your application’s behavior. Loguru is a Python library that provides simpler, more intuitive logging compared to Python’s built-in logging module.

Good logging gives you insights into your program’s execution, helps you diagnose issues, and provides valuable information about your application’s health in production. Without proper logging, you risk missing critical errors, spending countless hours debugging blind spots, and potentially undermining your project’s overall stability.

By the end of this tutorial, you’ll understand that:

  • Logging in Python can be simple and intuitive with the right tools.
  • Using Loguru lets you start logging immediately without complex configuration.
  • You can customize log formats and send logs to multiple destinations like files, the standard error stream, or external services.
  • You can implement automatic log rotation and retention policies to manage log files effectively.
  • Loguru provides powerful debugging capabilities that make troubleshooting easier.
  • Loguru supports structured logging with JSON formatting for modern applications.

After reading this tutorial, you’ll be able to quickly implement better logging in your Python applications. You’ll spend less time wrestling with logging configuration and more time using logs effectively to debug issues. This will help you build production-ready applications that are easier to troubleshoot when problems occur.

To get the most from this tutorial, you should be familiar with Python concepts like functions, decorators, and context managers. You might also find it helpful to have some experience with Python’s built-in logging module, though this isn’t required.

Don’t worry if you’re new to logging in Python. This tutorial will guide you through everything you need to know to get started with Loguru and implement effective logging in your applications.

You’ll do parts of the coding for this tutorial in the Python standard REPL, and some other parts with Python scripts. You’ll find full script examples in the materials of this tutorial. You can download these scripts by clicking the link below:

Take the Quiz: Test your knowledge with our interactive “Python Logging With the Loguru Library” quiz. You’ll receive a score upon completion to help you track your learning progress:


Interactive Quiz

Python Logging With the Loguru Library

Think you know Python logging? Take this quick Loguru quiz to test your knowledge of formatting, sinks, rotation, and more!

Installing Loguru

Loguru is available on PyPI, and you can install it with pip. Open a terminal or command prompt, create a new virtual environment, and then install the library:

Language: Windows PowerShell
PS> python -m venv venv
PS> venv\Scripts\activate
(venv) PS> python -m pip install loguru
Language: Shell
$ python -m venv venv/
$ source venv/bin/activate
(venv) $ python -m pip install loguru

This command will install the latest version of Loguru from Python Package Index (PyPI) onto your machine.

Verifying the Installation

To verify that the installation was successful, start a Python REPL:

Language: Shell
(venv) $ python

Next, import Loguru:

Language: Python
>>> import loguru

If the import runs without error, then you’ve successfully installed Loguru and can now use it to log messages in your Python programs and applications.

Understanding Basic Setup Considerations

Before diving into Loguru’s features, there are a few key points to keep in mind:

  1. Single Logger Instance: Unlike Python’s built-in logging module, Loguru uses a single logger instance. You don’t need to create multiple loggers, just import the pre-configured logger object:

    Language: Python
    from loguru import logger
    
  2. Default Configuration: Out of the box, Loguru logs to stderr with a reasonable default format. This means you can start logging immediately without any setup.

  3. Python Version Compatibility: Loguru supports Python 3.5 and above.

Now that you understand these basic considerations, you’re ready to start logging with Loguru. In the next section, you’ll learn about basic logging operations and how to customize them to suit your needs.

Learning the Fundamentals of Logging With Loguru

One of Loguru’s main attractions is its simplicity compared to Python’s built-in logging module. Instead of writing multiple lines of configuration code, you can start logging immediately with a pre-configured logger.

This section will cover the fundamentals of using Loguru, from basic logging to more advanced features like custom formatting and log file management. You’ll learn how to implement effective logging with minimal setup while maintaining the flexibility to customize your logging as needed.

Getting Started With Zero Configuration

The most basic way to use Loguru is through its pre-configured logger object. Unlike Python’s built-in logging module, which requires explicit configuration before use, Loguru comes ready to use right after you import it.

You can start logging messages immediately with several logging methods that correspond to different severity levels:

Language: Python
>>> from loguru import logger

>>> logger.debug("Debug message")
2025-02-01 11:38:50.215 | DEBUG    | __main__:<module>:1 - Debug message

>>> logger.info("Info message")
2025-02-01 11:38:50.216 | INFO     | __main__:<module>:1 - Info message

>>> logger.error("Error message")
2025-02-01 11:38:51.420 | ERROR    | __main__:<module>:1 - Error message

When you run this code, you’ll see that each message is automatically formatted with useful information like the timestamp, log level, and the location of the log call:

Loguru Basic Usage

The default output includes color-coded levels when logging to a terminal, making it possible to quickly identify different types of messages. Loguru automatically detects if your terminal supports colors and disables them if it doesn’t.

Now it’s time to take a closer look at the first logging message:

Language: Log File
2025-02-01 11:38:50.215 | DEBUG    | __main__:<module>:1 - Debug message

In the above message, you have the following information:

  • 2025-02-01 11:38:50.215: Timestamp with millisecond precision
  • DEBUG: Log level indicating message severity
  • __main__: The module name where the log was called
  • <module>: The function or scope—in this case, module level
  • 1: Line number in the source code
  • Debug message: The actual message being logged

Each component is separated by a special character, such as a pipe (|) or a dash (-), for readability, and you can customize this format, as you’ll learn later in this tutorial.

Logs are sent to the standard error stream (stderr), which is the output channel that Loguru uses by default. It’s traditionally used for error messages and diagnostic output, making it ideal for logging since it can be separated from your program’s regular output. You can change this later when you need more complex logging setups. For example, you can send logs to files, network services, or multiple destinations at once.

Now that you understand the basics of logging with Loguru, next, you’ll explore how to categorize your messages by importance. Loguru provides several log levels that let you distinguish between different types of information, from detailed debugging output to critical errors.

Understanding Log Levels

Now that you’re familiar with basic logging, you’ll explore Loguru’s log levels in more detail. Log levels help you categorize messages based on their severity and importance, allowing you to filter and manage your logs effectively.

Loguru provides seven built-in log levels, each with its own method, severity value, and default color scheme:

Level Method Value Purpose
TRACE logger.trace() 5 Extremely detailed information for debugging
DEBUG logger.debug() 10 Information useful during development
INFO logger.info() 20 General information about what’s happening in the code
SUCCESS logger.success() 25 Notifications of successful operations
WARNING logger.warning() 30 Warnings about something unexpected but not necessarily problematic
ERROR logger.error() 40 Errors for when something fails but the application continues running