Loguru: The Most Powerful Logging Library in Python!

Today, let's talk about a particularly practical but lesser-known Python library—Loguru. This is a tool that makes logging incredibly simple! Whether you're a beginner or a veteran, using it can make your logging work much more efficient. Why use Loguru? To be honest, Python's built-in logging module is like playing with building blocks—it's complex to configure and prone to errors. But Loguru is different; it's like a "point-and-shoot camera," ready to use out of the box and incredibly powerful.



Installation

Installing Loguru is super simple, just one command:

pip install loguru

Basic Usage Let's look at the most basic usage, I guarantee you'll get it in one read:

from loguru import logger

# The simplest logging
logger.debug("Debug info: The program is executing...")
logger.info("General info: Task completed!")
logger.warning("Warning info: High memory usage")
logger.error("Error info: Failed to connect to the database")

Isn't it super simple? No configuration needed, just import and use!

Advanced Features

  1. Output to a file
from loguru import logger

# Output to a file with log rotation
logger.add("app.log", rotation="500 MB", compression="zip")

def process_data():
    logger.info("Starting to process data...")
    try:
        result = 10 / 0  # Intentionally causing an error
    except Exception as e:
        logger.exception(f"Data processing error: {e}")

process_data()

This example will automatically create a log file, and when the file size exceeds 500MB, it will automatically compress and archive, which is great for long-running programs!

  1. Customize log format
from loguru import logger
import sys

# Customize log format
logger.remove()  # Remove default handler
logger.add(sys.stderr, format="<green>{time:YYYY-MM-DD HH:mm:ss}</green> | <level>{level}</level> | <cyan>{name}</cyan>:<cyan>{function}</cyan>:<cyan>{line}</cyan> - <level>{message}</level>")

def check_status():
    logger.info("Checking system status")
    logger.warning("Potential issue detected")

check_status()

Look at this colorful output, isn't it especially cool? And the information is clear at a glance!

  1. Capture detailed exceptions
from loguru import logger

@logger.catch
def calculate_average(numbers):
    total = sum(numbers)
    average = total / len(numbers)
    return average

# Test the function
try:
    result = calculate_average([])  # An empty list will cause an error
except Exception as e:
    logger.error("Error occurred while calculating the average")

Using the @logger.catch decorator, you can automatically capture and log detailed error information, including the complete stack trace, which is incredibly useful for debugging!

Real-world example: Monitoring a file processing program Let's look at a practical example, suppose we need to monitor a file processing program:

from loguru import logger
import time

# Configure logging
logger.add(
    "file_processor.log",
    rotation="1 day",
    retention="7 days",
    level="INFO"
)

class FileProcessor:
    def __init__(self):
        logger.info("File processor initialized")

    def process_file(self, filename):
        logger.info(f"Starting to process file: {filename}")
        try:
            # Simulate file processing
            time.sleep(1)
            if "test" in filename:
                raise ValueError("Test files are not allowed to be processed")
            logger.success(f"File {filename} processed successfully")
        except Exception as e:
            logger.error(f"Error processing file {filename}{str(e)}")

# Usage example
processor = FileProcessor()
processor.process_file("document.txt")
processor.process_file("test.txt")

Tips

  • Loguru's log levels: trace: most detailed logs, debug: debug information, info: general information, success: success information, warning: warning information, error: error information, critical: critical errors.
  • Log file rotation supports various methods: by size: rotation="100 MB", by time: rotation="00:00", by day: rotation="1 day".
  • Do not frequently create log files in loops.
  • Remember to set the appropriate log level.
  • Pay attention to permission issues with log files.
  • Use the exception capture decorator reasonably.

Folks, that's it for today's Python logging tool study!

发表评论

后一页 前一页