core/services/logger.py

71 lines
2.0 KiB
Python
Raw Normal View History

2024-02-20 14:49:21 +00:00
import logging
import colorlog
2024-02-20 16:23:38 +00:00
# Define the color scheme
color_scheme = {
2024-02-21 07:27:16 +00:00
"DEBUG": "light_black",
"INFO": "green",
"WARNING": "yellow",
"ERROR": "red",
"CRITICAL": "red,bg_white",
2024-02-20 16:23:38 +00:00
}
# Define secondary log colors
secondary_colors = {
2024-02-21 07:27:16 +00:00
"log_name": {"DEBUG": "blue"},
"asctime": {"DEBUG": "cyan"},
"process": {"DEBUG": "purple"},
"module": {"DEBUG": "light_black,bg_blue"},
2024-02-20 16:23:38 +00:00
}
2024-02-20 16:33:24 +00:00
# Define the log format string
fmt_string = "%(log_color)s%(levelname)s: %(log_color)s[%(module)s]%(reset)s %(white)s%(message)s"
# Define formatting configuration
fmt_config = {
2024-02-21 07:27:16 +00:00
"log_colors": color_scheme,
"secondary_log_colors": secondary_colors,
"style": "%",
"reset": True,
2024-02-20 16:33:24 +00:00
}
2024-02-21 07:27:16 +00:00
2024-02-20 16:33:24 +00:00
class MultilineColoredFormatter(colorlog.ColoredFormatter):
def format(self, record):
# Check if the message is multiline
2024-02-21 07:27:16 +00:00
if record.getMessage() and "\n" in record.getMessage():
2024-02-20 16:33:24 +00:00
# Split the message into lines
2024-02-21 07:27:16 +00:00
lines = record.getMessage().split("\n")
2024-02-20 16:33:24 +00:00
formatted_lines = []
for line in lines:
# Format each line with the provided format
2024-02-20 16:45:55 +00:00
formatted_lines.append(super().format(record))
2024-02-20 16:33:24 +00:00
# Join the formatted lines
2024-02-21 07:27:16 +00:00
return "\n".join(formatted_lines)
2024-02-20 16:33:24 +00:00
else:
# If not multiline or no message, use the default formatting
return super().format(record)
2024-02-20 16:42:14 +00:00
# Create a MultilineColoredFormatter object for colorized logging
2024-02-20 16:37:20 +00:00
formatter = MultilineColoredFormatter(fmt_string, **fmt_config)
# Create a stream handler for logging output
stream = logging.StreamHandler()
stream.setFormatter(formatter)
2024-02-20 16:33:24 +00:00
2024-02-21 07:27:16 +00:00
def get_colorful_logger(name="main"):
2024-02-20 15:16:17 +00:00
# Create and configure the logger
2024-02-20 14:49:21 +00:00
logger = logging.getLogger(name)
logger.setLevel(logging.DEBUG)
logger.addHandler(stream)
return logger
2024-02-20 16:19:46 +00:00
2024-02-21 07:27:16 +00:00
2024-02-20 16:33:24 +00:00
# Set up the root logger with the same formatting
2024-02-20 16:23:38 +00:00
root_logger = logging.getLogger()
2024-02-20 16:33:24 +00:00
root_logger.setLevel(logging.DEBUG)
2024-02-20 16:37:20 +00:00
root_logger.addHandler(stream)