This snippet sets up a logger that writes log messages to both the console and a file, with different log levels to capture various types of information.
import logging
import os
# Create a directory for logs if it doesn't exist
if not os.path.exists('logs'):
os.makedirs('logs')
# Configure the logger
logging.basicConfig(
level=logging.DEBUG, # Set the logging level
format='%(asctime)s - %(name)s - %(levelname)s - %(message)s',
handlers=[
logging.FileHandler('logs/app.log'), # Log to a file
logging.StreamHandler() # Log to the console
]
)
# Get the logger instance
logger = logging.getLogger('MyAppLogger')
# Example usage of the logger
def divide_numbers(x, y):
try:
logger.debug(f"Attempting to divide {x} by {y}")
result = x / y
logger.info(f"Division successful: {result}")
return result
except ZeroDivisionError as e:
logger.error("Division by zero error", exc_info=True)
except Exception as e:
logger.exception("An unexpected error occurred")
# Demonstrate logging in action
if __name__ == "__main__":
divide_numbers(10, 2) # Normal operation
divide_numbers(10, 0) # Division by zero