128. Contextual Logging with logging
1. Basic Logging Setup
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 shown2. Setting Dynamic Logging Level
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")3. Logging to a File
4. Logging with Different Formats
5. Logging with Rotating Files
6. Using a Logger with Multiple Handlers
7. Custom Logging Levels
8. Contextual Logging with extra
extra9. Loggers with Multiple Sources
10. Timed Logging with logging.handlers.TimedRotatingFileHandler
logging.handlers.TimedRotatingFileHandlerLast updated