loggersetupper
The code contained loggersetupper.py defines a custom logging setup for Python applications, giving the default logging with features like file rotation, colored output on the console, and customizable log formatting.
1. Colors Class:
class Colors:
BLACK = 'black'
RED = 'red'
GREEN = 'green'
YELLOW = 'yellow'
BLUE = 'blue'
MAGENTA = 'magenta'
CYAN = 'cyan'
WHITE = 'white'
# Text styles
BOLD = 'bold'
DARK = 'dark'
UNDERLINE = 'underline'
REVERSE = 'reverse'
-
Purpose: This class defines constants for various colors and text styles that can be used for customizing the log output. The colors are used for log levels and field styling, while the text styles like
BOLD,UNDERLINE, etc., allow for additional formatting. -
Usage: The colors and styles defined here can be applied to the log messages to make them more readable or visually distinguishable based on log level or field type.
2. Helper Methods in Colors Class:
def create_style(*args):
"""Create a custom style combining colors and attributes"""
return set(args)
def combine_styles(style1, style2):
"""Combine two styles into one"""
return style1.union(style2)
- Purpose:
create_style: This method allows the creation of a custom style by combining various colors and attributes.combine_styles: This method combines two existing styles into one, useful when you need to merge different formatting styles.
3. Log Format and Date Format:
LOG_FORMAT = '%(asctime)s - %(name)s:%(hostname)s - %(levelname)s - %(message)s'
DATE_FORMAT = '%Y-%m-%d %H:%M:%S'
- Purpose:
LOG_FORMAT: Specifies the format of the log message, which includes the timestamp (asctime), the logger's name (name), the hostname (hostname), the log level (levelname), and the actual log message (message).DATE_FORMAT: Specifies the format for the date in the logs, which isYYYY-MM-DD HH:MM:SS.
4. setup_logger Function:
def setup_logger(name='YetiForceWrapper', log_file='YetiForceWrapper.log', level=logging.DEBUG, levelstyle=None, fieldstyle=None):
-
Purpose: This function sets up a logger with both console and file logging, and allows customization of the log format, log levels, and field styles.
-
Parameters:
name: The name of the logger, default is'YetiForceWrapper'.log_file: The log file name where logs will be stored. Default is'YetiForceWrapper.log'.level: The logging level, default islogging.DEBUG. It determines the minimum severity of messages that will be logged (e.g.,DEBUG,INFO,WARNING,ERROR,CRITICAL).levelstyle: Custom styling for different log levels, passed as a dictionary.fieldstyle: Custom styling for the log fields, passed as a dictionary.
5. Logger Setup Steps:
-
Logger Creation:
logger = logging.getLogger(name): A logger instance is created with the given name.logger.setLevel(level): The logger's logging level is set.
-
Handlers:
console_handler: AStreamHandleris created for printing log messages to the console.file_handler: ARotatingFileHandleris created to store log messages in a file with a maximum size of 1MB. Once the file exceeds 1MB, it rotates (backs up the file and creates a new one).console_handler.setLevel(logging.DEBUG): Sets the console handler's logging level toDEBUG, so all messages at this level or above are logged to the console.file_handler.setLevel(logging.INFO): Sets the file handler's logging level toINFO, meaning only messages of levelINFOor higher will be logged to the file.
-
Formatters:
file_formatter = logging.Formatter(LOG_FORMAT, DATE_FORMAT): A formatter is applied to the file handler to define the log format.file_handler.setFormatter(file_formatter): The formatter is set for the file handler.
-
Colored Output:
coloredlogs.install: This is used to install colored log output in the console. Thelevel_stylesandfield_stylesdictionaries define how different log levels and fields should be styled (color and text attributes like bold, underline, etc.). The default styles are set in the code.
6. Return the Logger:
return logger
- The configured logger is returned so it can be used elsewhere in the code to log messages.
Example Usage:
You can call setup_logger() to create a logger and start logging messages:
logger = setup_logger()
# Example log messages
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")
- The messages will be logged to both the console (with color formatting) and a log file (
YetiForceWrapper.log), with different levels of severity controlling which messages are shown in the console and logged in the file.
Purpose of the Code:
- Enhanced Logging: This code provides an advanced logging system that logs messages both to the console (with color coding) and to a rotating log file.
- Log Customization: It allows for flexible customization of the log output, including the log format, log level, and color styling for various log levels and fields.
- Efficient Log Management: The use of
RotatingFileHandlerensures that the log files do not grow indefinitely, and old logs are backed up when the log file exceeds a certain size.
In summary, this code sets up a logging system that is useful for applications that require organized, readable, and well-maintained log files, with colorful output on the console for easier debugging and monitoring.