Logging exceptions is crucial for:
logging
ModulePython’s built-in logging
module provides a flexible framework for emitting log messages from Python programs. It’s designed to meet the needs of simple scripts as well as complex applications.
To log exceptions, you first need to set up a logger.
import logging
logging.basicConfig(level=logging.ERROR, format='%(asctime)s - %(levelname)s - %(message)s')
You can log an exception within an except
block using logging.error
with exc_info=True
to include the traceback.
try:
result = 10 / 0
except ZeroDivisionError as e:
logging.error("An error occurred: %s", e, exc_info=True)
The logging
module provides several levels of logging, which indicate the severity of events.
You can customize the log format to include various details like time, level, and message.
logging.basicConfig(level=logging.ERROR,
format='%(asctime)s - %(name)s - %(levelname)s - %(message)s',
datefmt='%Y-%m-%d %H:%M:%S')
For more complex applications, it’s beneficial to create logger objects.
logger = logging.getLogger(__name__)
logger.setLevel(logging.ERROR)
try:
result = 10 / 0
except ZeroDivisionError as e:
logger.error("Zero Division Error occurred", exc_info=True)
Instead of logging to the console, you can log to a file by configuring a FileHandler
.
file_handler = logging.FileHandler('app.log')
file_handler.setLevel(logging.ERROR)
formatter = logging.Formatter('%(asctime)s - %(name)s - %(levelname)s - %(message)s')
file_handler.setFormatter(formatter)
logger.addHandler(file_handler)
try:
result = 10 / 0
except ZeroDivisionError as e:
logger.error("Zero Division Error occurred", exc_info=True)
To avoid a single large log file, you can use RotatingFileHandler
to create rotating logs.
from logging.handlers import RotatingFileHandler
rotating_handler = RotatingFileHandler('app.log', maxBytes=2000, backupCount=5)
rotating_handler.setLevel(logging.ERROR)
rotating_handler.setFormatter(formatter)
logger.addHandler(rotating_handler)
try:
result = 10 / 0
except ZeroDivisionError as e:
logger.error("Zero Division Error occurred", exc_info=True)