This Python script provides a utility function setup_logger to easily create a logger that outputs messages to both the console (with colors!) and a file. It leverages the standard logging module and the colorama library for cross-platform colored terminal text.
- Colored Console Output: Log messages are displayed in different colors based on their severity level (DEBUG, INFO, WARNING, ERROR, CRITICAL), making them easier to distinguish in the console.
- File Logging: All log messages are also written to a timestamped log file.
- Customizable Log Directory: You can specify the directory where log files will be saved.
- Optional Separate Log Directories: You can choose to create a new, timestamped subdirectory for each run of your script.
- Automatic Log Filename: By default, the log file is named based on the script that initiated the logging and includes a timestamp. You can also provide a custom log filename.
- Configurable Log Level: You can set the minimum severity level for messages to be logged (e.g., only log WARNING and above).
- Python 3.6 or higher
coloramalibrary.
To use the setup_logger function in your Python script, follow these steps:
-
Import the function:
from setup_logger import setup_logger
-
Call
setup_logger()to get a logger instance:logger = setup_logger()
You can customize the logger by providing arguments:
log_dir(str, optional): The directory to save log files. Defaults to./logs/.log_name(str, optional): The base name for the log file. IfNone(default), it will be based on the calling module's name.log_level(str, optional): The logging level. Can be'debug','info','warning', or'error'. Defaults to'info'.separate_dirs(bool, optional): IfTrue, log files will be created in a new subdirectory withinlog_dir, named with a timestamp. Defaults toFalse.
-
Use the logger instance to record messages:
logger.debug('This is a debug message.') logger.info('This is an informational message.') logger.warning('This is a warning message.') logger.error('This is an error message.') logger.critical('This is a critical message.')
The setup_logger function configures a logger that produces output in two places:
-
Console (Standard Output): Log messages are printed to the console with color-coding based on the log level:
- DEBUG: Blue</style>
- INFO: Green</style>
- WARNING: Yellow</style>
- ERROR: Red</style>
- CRITICAL: Bright Red</style>
Each message is formatted as:
YYYY-MM-DD HH:MM:SS,ms - LEVEL - MESSAGE
- Log File: A text file is created in the specified
log_dir(defaulting to./logs/). The filename includes the log name (or the calling script's name) and a timestamp of when the logger was initialized. The format of the messages in the log file is the same as the console output, but without the color codes.
This logger provides a convenient way to track script execution and identify potential issues.
Here are a few examples of how to use the setup_logger function with different configurations:
# your_script_name.py
from setup_logger import setup_logger
import time
logger = setup_logger()
logger.debug("A detailed debug message.")
logger.info("Script started.")
logger.warning("Something might not be right.")
logger.error("An error occurred!")
logger.critical("A critical issue needs immediate attention.")Output in the console (with colors):
2025-05-14 12:20:00,000 - DEBUG - A detailed debug message.
2025-05-14 12:20:00,000 - INFO - Script started.
2025-05-14 12:20:01,000 - WARNING - Something might not be right.
2025-05-14 12:20:01,000 - ERROR - An error occurred!
2025-05-14 12:20:01,000 - CRITICAL - A critical issue needs immediate attention.
Log file (./logs/your_script_name_2025-05-14__12-20-00.log):
2025-05-14 12:20:00,000 - DEBUG - A detailed debug message.
2025-05-14 12:20:00,000 - INFO - Script started.
2025-05-14 12:20:01,000 - WARNING - Something might not be right.
2025-05-14 12:20:01,000 - ERROR - An error occurred!
2025-05-14 12:20:01,000 - CRITICAL - A critical issue needs immediate attention.
# your_script_name.py
from setup_logger import setup_logger
import time
logger = setup_logger(log_dir='./my_app_logs', log_level='warning')
logger.info("This info message will not be logged (level is 'warning').")
logger.warning("This warning will be logged.")
logger.error("An error will also be logged.")Output in the console (with colors):
2025-05-14 12:20:00,000 - WARNING - This warning will be logged.
2025-05-14 12:20:00,000 - ERROR - An error will also be logged.
Log file (./my_app_logs/your_script_name_2025-05-14__12-20-00.log):
2025-05-14 12:20:00,000 - WARNING - This warning will be logged.
2025-05-14 12:20:00,000 - ERROR - An error will also be logged.