SoFunction
Updated on 2025-03-02

Introduction to Python log library Logoru

loguruIt is a very convenient and powerful Python log library that makes logging simple and intuitive.

Main features

  • Simple and easy to use: Compared with built-inloggingModule,loguruThe API is simpler and easier to use.
  • automation: Automatically handle log format, file management, exception capture, etc.
  • Flexible configuration: Supports various output formats, file rotation, filter and other advanced functions.
  • Multi-threaded safety: Supports logging of multi-threaded and asynchronous applications.
  • Rich features: Supports rich log levels, exception information, context information, etc.

Basic usage

Install

Can be installed via piploguru

pip install loguru

Introduced

from loguru import logger

Basic configuration

("", rotation="1 MB")  # Automatically rotate by file size

Log Level

loguruMultiple log levels are provided, and the default ones include the following:

  • TRACE(0)
  • DEBUG(10)
  • INFO(20)
  • SUCCESS(25)
  • WARNING(30)
  • ERROR(40)
  • CRITICAL(50)

Example:

("This is a debug message")
("This is an info message")
("This is a warning message")
("This is an error message")
("This is a critical message")

Catch exceptions

useloggerWhen catching exceptions, you can output a detailed traceback:

try:
    1 / 0  # Intentionally causing division by zero errorexcept ZeroDivisionError:
    ("An error occurred:\n{}", traceback.format_exc())

Log file management

loguruSupports rotation and compression of log files:

("file_{time}.log", rotation="1 day", retention="7 days", compression="zip")

This will create a new log file every day, keep it for 7 days, and compress the old log file into ZIP format.

Add context information

Available()Add context information:

with (user="user1"):
    ("User logged in")

This will make the log information contain the user context.

Advanced features

Filter: You can filter log output based on log level or other conditions.

("", filter=lambda record: record["level"].name == "ERROR")

Format: You can customize the output format of the log.

("", format="{time} {level} {message}")

Asynchronous support: used in asynchronous programsloguruVery simple, too. Summarize

loguruIt is a powerful and easy to use log library suitable for projects of all sizes. Whether it is simple scripts or complex applications, it provides convenient logging capabilities. Through flexible configuration and powerful features,loguruCan help developers handle logging tasks easily.

This is all about this article about the introduction of Python Logoru. For more related Python Logoru content, please search for my previous articles or continue browsing the related articles below. I hope everyone will support me in the future!