55. Debugging with logging Module

1. Basic Logging Setup

Setting up basic logging configuration.

Copy

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.

Copy

This configuration writes log messages to app.log file, allowing for permanent logging.


3. Customizing Log Message Format

Customizing the format of log messages.

Copy

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.

Copy

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.

Copy

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.

Copy

This code uses the extra argument to add custom context (like user and action) to log records.


7. Logging Exceptions

Logging exceptions with traceback.

Copy

The logging.exception() method logs the exception along with the traceback.


8. Dynamic Log Level Adjustment

Dynamically changing the log level at runtime.

Copy

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.

Copy

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.

Copy

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