Home Backend Development Python Tutorial Mastering Python Logging: From Basics to Advanced Techniques

Mastering Python Logging: From Basics to Advanced Techniques

Dec 04, 2024 am 08:25 AM

Logging in Python is more than just debugging—it's about tracking, monitoring, and understanding your application’s behavior. Whether you're a beginner or an experienced developer, this guide covers all aspects of logging, from basic setups to advanced techniques.

Mastering Python Logging: From Basics to Advanced Techniques

Introduction
What is logging?
Logging is a mechanism to record and track events during the execution of a program, helping developers debug, monitor, and analyze their applications effectively.

Why is logging essential?
Unlike print, logging offers flexibility, scalability, and configurability, making it a robust choice for both small scripts and large applications.

What this blog covers
Setting up basic logging
Writing logs to files
Creating custom loggers
Formatting log outputs
Advanced techniques like log rotation and configurations
Best practices and common mistakes

What is Logging in Python?
Introduce the logging module.
Explain logging levels:
DEBUG: Detailed information for diagnosing issues.
INFO: Confirmation that the program is working as expected.
WARNING: Something unexpected happened, but the program can still run.
ERROR: A problem caused an operation to fail.
CRITICAL: A serious error that might stop the program.

Setting Up Basic Logging
Introduce logging.basicConfig.
Provide a simple example:

import logging

# Basic configuration
logging.basicConfig(level=logging.INFO)

# Logging messages
logging.debug("Debug message")
logging.info("Info message")
logging.warning("Warning message")
logging.error("Error message")
logging.critical("Critical message")
Copy after login
Copy after login

Output
By default, only messages at WARNING level or above are displayed on the console. The above example produces:

WARNING:root:Warning message
ERROR:root:Error message
CRITICAL:root:Critical message

Writing Logs to a File

logging.basicConfig(filename="app.log", 
                    level=logging.DEBUG, 
                    format="%(asctime)s - %(levelname)s - %(message)s")

logging.info("This will be written to a file.")
Copy after login

Explain common parameters in basicConfig:
filename: Specifies the log file.
filemode: 'w' to overwrite or 'a' to append.
format: Customizes log message structure.

Creating Custom Loggers
Why use custom loggers? For modular and more controlled logging.
Example:

import logging

# Create a custom logger
logger = logging.getLogger("my_logger")
logger.setLevel(logging.DEBUG)

# Create handlers
console_handler = logging.StreamHandler()
file_handler = logging.FileHandler("custom.log")

# Set levels for handlers
console_handler.setLevel(logging.INFO)
file_handler.setLevel(logging.ERROR)

# Create formatters and add them to handlers
formatter = logging.Formatter("%(name)s - %(levelname)s - %(message)s")
console_handler.setFormatter(formatter)
file_handler.setFormatter(formatter)

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

# Log messages
logger.info("This is an info message.")
logger.error("This is an error message.")
Copy after login

** Formatting Logs**
Explain log record attributes:
%(asctime)s: Timestamp.
%(levelname)s: Level of the log message.
%(message)s: The actual log message.
%(name)s: Logger's name.
Advanced formatting:

logging.basicConfig(format="%(asctime)s - %(name)s - %(levelname)s - %(message)s",
                    datefmt="%Y-%m-%d %H:%M:%S",
                    level=logging.DEBUG)
Copy after login

Log Rotation
Introduce RotatingFileHandler for managing log file size.
Example:

from logging.handlers import RotatingFileHandler

# Create a logger
logger = logging.getLogger("rotating_logger")
logger.setLevel(logging.DEBUG)

# Create a rotating file handler
handler = RotatingFileHandler("app.log", maxBytes=2000, backupCount=3)
formatter = logging.Formatter("%(asctime)s - %(levelname)s - %(message)s")
handler.setFormatter(formatter)

logger.addHandler(handler)

# Log messages
for i in range(100):
    logger.info(f"Message {i}")
Copy after login

Using logging.config for Complex Configurations
Show how to use a configuration dictionary:

import logging

# Basic configuration
logging.basicConfig(level=logging.INFO)

# Logging messages
logging.debug("Debug message")
logging.info("Info message")
logging.warning("Warning message")
logging.error("Error message")
logging.critical("Critical message")
Copy after login
Copy after login

Best Practices for Logging
Use meaningful log messages.
Avoid sensitive data in logs.
Use DEBUG level in development and higher levels in production.
Rotate log files to prevent storage issues.
Use unique logger names for different modules.

Common Mistakes
Overusing DEBUG in production.
Forgetting to close file handlers.
Not using a separate log file for errors.

Advanced Topics
Asynchronous Logging
For high-performance applications, use QueueHandler to offload logging tasks asynchronously.

Structured Logging
Log messages as JSON to make them machine-readable, especially for systems like ELK Stack.

Third-Party Libraries
Explore tools like loguru for simpler and more powerful logging.

Conclusion
Logging is not just about debugging—it's about understanding your application. By mastering Python's logging module, you can ensure your projects are robust, maintainable, and easy to debug.

Have questions or suggestions? Share your thoughts in the comments below!

The above is the detailed content of Mastering Python Logging: From Basics to Advanced Techniques. For more information, please follow other related articles on the PHP Chinese website!

Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

AI Hentai Generator

AI Hentai Generator

Generate AI Hentai for free.

Hot Article

R.E.P.O. Energy Crystals Explained and What They Do (Yellow Crystal)
3 weeks ago By 尊渡假赌尊渡假赌尊渡假赌
R.E.P.O. Best Graphic Settings
3 weeks ago By 尊渡假赌尊渡假赌尊渡假赌
R.E.P.O. How to Fix Audio if You Can't Hear Anyone
3 weeks ago By 尊渡假赌尊渡假赌尊渡假赌
WWE 2K25: How To Unlock Everything In MyRise
3 weeks ago By 尊渡假赌尊渡假赌尊渡假赌

Hot Tools

Notepad++7.3.1

Notepad++7.3.1

Easy-to-use and free code editor

SublimeText3 Chinese version

SublimeText3 Chinese version

Chinese version, very easy to use

Zend Studio 13.0.1

Zend Studio 13.0.1

Powerful PHP integrated development environment

Dreamweaver CS6

Dreamweaver CS6

Visual web development tools

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)

How to solve the permissions problem encountered when viewing Python version in Linux terminal? How to solve the permissions problem encountered when viewing Python version in Linux terminal? Apr 01, 2025 pm 05:09 PM

Solution to permission issues when viewing Python version in Linux terminal When you try to view Python version in Linux terminal, enter python...

How to efficiently copy the entire column of one DataFrame into another DataFrame with different structures in Python? How to efficiently copy the entire column of one DataFrame into another DataFrame with different structures in Python? Apr 01, 2025 pm 11:15 PM

When using Python's pandas library, how to copy whole columns between two DataFrames with different structures is a common problem. Suppose we have two Dats...

What are some popular Python libraries and their uses? What are some popular Python libraries and their uses? Mar 21, 2025 pm 06:46 PM

The article discusses popular Python libraries like NumPy, Pandas, Matplotlib, Scikit-learn, TensorFlow, Django, Flask, and Requests, detailing their uses in scientific computing, data analysis, visualization, machine learning, web development, and H

How to dynamically create an object through a string and call its methods in Python? How to dynamically create an object through a string and call its methods in Python? Apr 01, 2025 pm 11:18 PM

In Python, how to dynamically create an object through a string and call its methods? This is a common programming requirement, especially if it needs to be configured or run...

How does Uvicorn continuously listen for HTTP requests without serving_forever()? How does Uvicorn continuously listen for HTTP requests without serving_forever()? Apr 01, 2025 pm 10:51 PM

How does Uvicorn continuously listen for HTTP requests? Uvicorn is a lightweight web server based on ASGI. One of its core functions is to listen for HTTP requests and proceed...

How to teach computer novice programming basics in project and problem-driven methods within 10 hours? How to teach computer novice programming basics in project and problem-driven methods within 10 hours? Apr 02, 2025 am 07:18 AM

How to teach computer novice programming basics within 10 hours? If you only have 10 hours to teach computer novice some programming knowledge, what would you choose to teach...

What are regular expressions? What are regular expressions? Mar 20, 2025 pm 06:25 PM

Regular expressions are powerful tools for pattern matching and text manipulation in programming, enhancing efficiency in text processing across various applications.

See all articles