55. Debugging with logging Module
Here are 10 Python code snippets demonstrating how to use the logging module for implementing sophisticated logging systems to improve traceability:
1. Basic Logging Setup
Setting up basic logging configuration.
import logging
# Basic logging configuration
logging.basicConfig(level=logging.DEBUG)
# Example log statements
logging.debug("This is a debug message")
logging.info("This is an info message")
logging.warning("This is a warning message")
logging.error("This is an error message")
logging.critical("This is a critical message")This sets up the logging system to log messages at the DEBUG level and above, and it logs messages of various severity levels.
2. Logging to a File
Logging messages to a file with a specified log level.
import logging
# Logging to a file
logging.basicConfig(filename='app.log', level=logging.INFO)
logging.info("This is an info message saved to a file.")
logging.error("This is an error message saved to a file.")This configuration writes log messages to app.log file, allowing for permanent logging.
3. Customizing Log Message Format
Customizing the format of log messages.
This sets a custom format for the log messages, including timestamps, logger name, log level, and the message.
4. Logging with Rotating Log Files
Using a rotating file handler for log files that grow too large.
This configuration creates a log file that rotates when it exceeds 2000 bytes, keeping up to 3 backups.
5. Logging with Multiple Handlers
Configuring multiple logging handlers to log to both a file and the console.
This example shows how to log to both a file and the console, with different log levels for each handler.
6. Log Record Creation
Creating custom log records with extra context.
This code uses the extra argument to add custom context (like user and action) to log records.
7. Logging Exceptions
Logging exceptions with traceback.
The logging.exception() method logs the exception along with the traceback.
8. Dynamic Log Level Adjustment
Dynamically changing the log level at runtime.
This demonstrates how to change the logging level dynamically at runtime.
9. Creating a Custom Logging Handler
Creating a custom log handler to log to a database or external system.
This creates a custom handler to log messages to an external system (like a database).
10. Logging in Multithreaded Applications
Handling logging in multithreaded applications with thread-specific loggers.
This snippet creates individual loggers for each thread to prevent interference in multithreaded applications.
These snippets demonstrate various ways to implement logging in Python for better traceability and debugging, including logging to files, customizing formats, handling exceptions, and working with multithreaded applications.
Last updated