128. Contextual Logging with logging

The logging module in Python provides a flexible framework for logging messages from Python programs. You can easily control the severity level of messages (e.g., debug, info, warning, error, critical) and configure the output format. Below are a few examples that demonstrate how to implement dynamic logging levels, format messages, and customize the logging behavior.

1. Basic Logging Setup

This example shows how to configure logging with a basic setup to log messages at different levels.

Copy

import logging

# Basic configuration of logging with default level (WARNING)
logging.basicConfig()

logging.debug("This is a debug message")  # Will not show, because default level is WARNING
logging.info("This is an info message")  # Will not show, because default level is WARNING
logging.warning("This is a warning message")  # Will be shown
logging.error("This is an error message")  # Will be shown
logging.critical("This is a critical message")  # Will be shown

2. Setting Dynamic Logging Level

You can dynamically change the logging level by configuring the logger object directly.

Copy

import logging

# Create a custom logger
logger = logging.getLogger('my_logger')

# Set the logging level to DEBUG
logger.setLevel(logging.DEBUG)

# Create a console handler to display logs
console_handler = logging.StreamHandler()

# Set the log format
formatter = logging.Formatter('%(asctime)s - %(name)s - %(levelname)s - %(message)s')
console_handler.setFormatter(formatter)

# Add the handler to the logger
logger.addHandler(console_handler)

logger.debug("This is a debug message")
logger.info("This is an info message")
logger.warning("This is a warning message")
logger.error("This is an error message")
logger.critical("This is a critical message")

Output:

Copy


3. Logging to a File

You can log messages to a file rather than the console by using a file handler.

Copy

The messages will be saved in the app.log file with the specified format.


4. Logging with Different Formats

You can customize the log format to include different details such as the line number, function name, and log message.

Copy


5. Logging with Rotating Files

To prevent log files from growing too large, you can use logging.handlers.RotatingFileHandler to create rotating log files.

Copy

This will create an app.log file that rotates after it reaches 2000 bytes, keeping up to 3 backup files.


6. Using a Logger with Multiple Handlers

You can set up multiple handlers (e.g., console and file logging) with different logging levels.

Copy


7. Custom Logging Levels

You can create custom logging levels by subclassing the logging.Level class.

Copy


8. Contextual Logging with extra

Use the extra keyword to pass additional context information to the log messages.

Copy


9. Loggers with Multiple Sources

You can use multiple loggers for different parts of your application.

Copy


10. Timed Logging with logging.handlers.TimedRotatingFileHandler

This handler allows you to rotate log files based on time intervals.

Copy

This will rotate the log file every midnight and keep 5 backup files.


These snippets illustrate how you can implement dynamic logging levels, customized message formatting, multiple logging outputs, and file rotation, making the logging module a versatile tool for handling logging in your applications.

Last updated