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

Video Face Swap

Video Face Swap

Swap faces in any video effortlessly with our completely free AI face swap tool!

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 avoid being detected by the browser when using Fiddler Everywhere for man-in-the-middle reading? How to avoid being detected by the browser when using Fiddler Everywhere for man-in-the-middle reading? Apr 02, 2025 am 07:15 AM

How to avoid being detected when using FiddlerEverywhere for man-in-the-middle readings When you use FiddlerEverywhere...

How to solve permission issues when using python --version command in Linux terminal? How to solve permission issues when using python --version command in Linux terminal? Apr 02, 2025 am 06:36 AM

Using python in Linux terminal...

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...

How to get news data bypassing Investing.com's anti-crawler mechanism? How to get news data bypassing Investing.com's anti-crawler mechanism? Apr 02, 2025 am 07:03 AM

Understanding the anti-crawling strategy of Investing.com Many people often try to crawl news data from Investing.com (https://cn.investing.com/news/latest-news)...

What is the reason why pipeline files cannot be written when using Scapy crawler? What is the reason why pipeline files cannot be written when using Scapy crawler? Apr 02, 2025 am 06:45 AM

Discussion on the reasons why pipeline files cannot be written when using Scapy crawlers When learning and using Scapy crawlers for persistent data storage, you may encounter pipeline files...

Python 3.6 loading pickle file error ModuleNotFoundError: What should I do if I load pickle file '__builtin__'? Python 3.6 loading pickle file error ModuleNotFoundError: What should I do if I load pickle file '__builtin__'? Apr 02, 2025 am 06:27 AM

Loading pickle file in Python 3.6 environment error: ModuleNotFoundError:Nomodulenamed...

See all articles