DEV Community

Cover image for Python Logging: loguru vs logging
Leapcell
Leapcell

Posted on

1 1 1 1 1

Python Logging: loguru vs logging

Image description

Python Logging Libraries Comparison: logging vs loguru

1. Loguru Simplifies Logging

Image description

In Python development, logging is a crucial tool. It helps developers record the running status of programs, debug issues, and monitor the health of systems. Python has the built - in logging library. However, with the changing requirements, many people have started to use loguru as an alternative. This article will compare these two libraries to help you choose a more suitable logging solution.

Loguru is a popular third - party logging library. It has become a powerful substitute for logging by simplifying the configuration process, supporting chained calls, and providing more abundant features.

Advantages of Loguru

  • Simple Configuration: Loguru doesn't require creating complex configurations. You can complete complex logging configurations with just a few lines of code.
  • Chained Calls: It supports chained calls, making logging more intuitive.
  • Multi - target Output: It can easily achieve logging output to both the console and files, and also supports rich format configurations.
  • Extra Features: It supports features such as automatic log compression, log file rotation, and log retention days.

Basic Example of Loguru

from loguru import logger

# Configure logging
logger.add("app.log", rotation="500 MB")  # The file will rotate automatically when it exceeds 500 MB

# Log messages
logger.info("This is an info message.")
logger.warning("This is a warning message.")
logger.error("This is an error message.")
Enter fullscreen mode Exit fullscreen mode

In this example, we don't need to configure multiple handlers additionally. Just calling logger.add() can easily complete the file logging configuration.

Output to Both File and Console

Loguru can very conveniently achieve output to both the file and the console:

from loguru import logger
import sys

# Add logging output to file and console
logger.add("app.log", rotation="500 MB", retention="10 days")  # File rotation and retention for 10 days
logger.add(sys.stdout, level="INFO")  # Output to the console

# Log messages
logger.info("This is an info message.")
logger.warning("This is a warning message.")
logger.error("This is an error message.")
Enter fullscreen mode Exit fullscreen mode

Here, logger.add(sys.stdout, level="INFO") can display the logs on the console without additional configuration.

2. Advantages and Disadvantages of Python's Built - in logging

Advantages

  • Part of the Standard Library: logging is part of the Python standard library, so there is no need for additional installation, and it is cross - platform.
  • Highly Customizable: logging provides powerful customization features, allowing flexible control of log formats, levels, and targets (files, consoles, remote servers, etc.).
  • Strong Compatibility: Many third - party libraries also use logging, enabling seamless integration of various logs.

Disadvantages

  • Complex Configuration: The basic use of logging is relatively simple, but slightly more complex configurations become lengthy and non - intuitive, especially when it is necessary to output to multiple targets (such as files and consoles) simultaneously.
  • No Chained Calls: logging does not support chained calls like loguru and requires layer - by - layer configuration.

Basic Example

A simple logging example of logging is as follows:

import logging

# Configure logging
logging.basicConfig(
    level = logging.INFO,
    format='%(asctime)s - %(levelname)s - %(message)s',
    filename='app.log',
    filemode='a'
)

# Log messages
logging.info("This is an info message.")
logging.warning("This is a warning message.")
logging.error("This is an error message.")
Enter fullscreen mode Exit fullscreen mode

In this example, the logs will be recorded in the app.log file but will not be displayed in the console. If we want to display the logs in both the console and the file, we need to configure StreamHandler additionally.

Configuration for Output to File and Console

To output logs to both the console and the file, we need to configure multiple Handlers. The code is as follows:

import logging

# Get the logger
logger = logging.getLogger()
logger.setLevel(logging.INFO)

# File handler
file_handler = logging.FileHandler('app.log')
file_handler.setFormatter(logging.Formatter('%(asctime)s - %(levelname)s - %(message)s'))

# Console handler
console_handler = logging.StreamHandler()
console_handler.setFormatter(logging.Formatter('%(asctime)s - %(levelname)s - %(message)s'))

# Add handlers to the logger
logger.addHandler(file_handler)
logger.addHandler(console_handler)

# Log messages
logger.info("This is an info message.")
logger.warning("This is a warning message.")
logger.error("This is an error message.")
Enter fullscreen mode Exit fullscreen mode

It can be seen that to achieve a relatively simple function, we need to create different Handlers and configure them one by one.

3. Detailed Comparison between logging and loguru

Feature logging loguru
Configuration Complexity High, need to set Handlers Low, only need logger.add()
File Rotation and Retention Need third - party module support Built - in support for rotation and retention
Output to Console and File Simultaneously Need to set multiple Handlers Easily achieved using sys.stdout
Chained Calls Not supported Supported
Ease of Use Suitable for complex configurations and integrations Suitable for rapid development and clear log management

4. Recommended Application Scenarios

  • Simple Applications and Rapid Development: Loguru is a better choice. It is concise and intuitive, suitable for rapid prototyping and small projects.
  • Complex Applications and Multi - module Projects: The highly customizable features provided by logging are more suitable for complex systems that require multi - level configurations, especially those projects that rely on third - party libraries and hope to unify log management.

5. Summary

Both loguru and logging have their advantages and disadvantages. For most Python projects, the concise syntax and powerful features of loguru make it the first choice for rapid development. For larger projects, the compatibility and flexibility of the standard library logging are more suitable. I hope this article can help you choose the appropriate logging tool for your project.

Leapcell: The Best Serverless Platform for Web Hosting

Image description

Finally, I would like to recommend the best platform for deploying Python apps: Leapcell

1. Multi - Language Support

  • Develop with JavaScript, Python, Go, or Rust.

2. Deploy unlimited projects for free

  • Pay only for usage — no requests, no charges.

3. Unbeatable Cost Efficiency

  • Pay - as - you - go with no idle charges.
  • Example: $25 supports 6.94M requests at a 60ms average response time.

4. Streamlined Developer Experience

  • Intuitive UI for effortless setup.
  • Fully automated CI/CD pipelines and GitOps integration.
  • Real - time metrics and logging for actionable insights.

5. Effortless Scalability and High Performance

  • Auto - scaling to handle high concurrency with ease.
  • Zero operational overhead — just focus on building.

Image description

Explore more in the documentation!

Leapcell Twitter: https://x.com/LeapcellHQ

Heroku

Simplify your DevOps and maximize your time.

Since 2007, Heroku has been the go-to platform for developers as it monitors uptime, performance, and infrastructure concerns, allowing you to focus on writing code.

Learn More

Top comments (1)

Collapse
 
mfachal profile image
Manuel Fachal

Thanks for sharing! It would be great to have a stress test comparison, to see which one is more efficient.

A Workflow Copilot. Tailored to You.

Pieces.app image

Our desktop app, with its intelligent copilot, streamlines coding by generating snippets, extracting code from screenshots, and accelerating problem-solving.

Read the docs

👋 Kindness is contagious

Explore a sea of insights with this enlightening post, highly esteemed within the nurturing DEV Community. Coders of all stripes are invited to participate and contribute to our shared knowledge.

Expressing gratitude with a simple "thank you" can make a big impact. Leave your thanks in the comments!

On DEV, exchanging ideas smooths our way and strengthens our community bonds. Found this useful? A quick note of thanks to the author can mean a lot.

Okay