python custom wrapped logging module with color
In the process of building a python interface automation framework to share some content, I would like to encapsulate a logger method based on logging for secondary encapsulation code is as follows
import logging import os import time import colorlog from import RotatingFileHandler # Create file directories cur_path = ((__file__)) # log_path is the path where the logs are stored log_path = ((cur_path), 'logs') if not (log_path): (log_path) # If this logs folder doesn't exist, it automatically creates a # Modify the log save location timestamp = ("%Y-%m-%d", ()) logfile_name = '%' % timestamp logfile_path = (log_path, logfile_name) # Define different log level colors log_colors_config = { 'DEBUG': 'bold_cyan', 'INFO': 'bold_green', 'WARNING': 'bold_yellow', 'ERROR': 'bold_red', 'CRITICAL': 'red', } class Logger(): def __init__(self, name, level='DEBUG', file=None, encoding='utf-8'): super().__init__(name) = encoding = file = level # Manually adjust the color for the desired log message formatter = ( '%(log_color)s%(levelname)1.1s %(asctime)s %(reset)s| %(message_log_color)s%(levelname)-8s %(reset)s| %(' 'log_color)s[%(filename)s%(reset)s:%(log_color)s%(module)s%(reset)s:%(log_color)s%(funcName)s%(' 'reset)s:%(log_color)s%(''lineno)d] %(reset)s- %(white)s%(message)s', reset=True, log_colors=log_colors_config, secondary_log_colors={ 'message': { 'DEBUG': 'blue', 'INFO': 'blue', 'WARNING': 'blue', 'ERROR': 'red', 'CRITICAL': 'bold_red' } }, style='%' ) # Log output format # Create a FileHandler for writing to local rotatingFileHandler = (filename=logfile_path, maxBytes=1024 * 1024 * 50, backupCount=5) (formatter) () (rotatingFileHandler) # Create a StreamHandler for output to the console. console = () () (formatter) (console) () logger = Logger(name=logfile_path, file=logfile_path)
To use it, we just need to introduce the encapsulated class Intuitive and beautiful ~
# Introduce a wrapped logger module from common.logger_handler import logger def physical_strength(self, abnormal): """Generalized method of redeeming stamina anomalies.""" if .__contains__('costType'): attrs_Type = { "costType": abnormal, "count": ["count"] } response_Type = r().response(self.send_uid, , , attrs_Type) # Just call () when you use it. (f"physical_strength_{abnormal},response_Type:{response_Type}") assert response_Type["code"] != 0 (2) attrs_count = { "costType": ["costType"], "count": abnormal } response_count = r().response(self.send_uid, , , attrs_count) (f"physical_strength_{abnormal},response_count:{response_count}") assert response_count["code"] != 0 (2) attrs_all = { "costType": abnormal, "count": abnormal } response_all = r().response(self.send_uid, , , attrs_all) (f"physical_strength_{abnormal},response_all:{response_all}") assert response_all["code"] != 0 (2) else: attrs_count = { "count": abnormal } response_count = r().response(self.send_uid, , , attrs_count) (f"physical_strength_{abnormal},response_count:{response_count}") assert response_count["code"] != 0 (2)
Effect: display by date/time/log level/file name/class/method name/line of code (here you can manually adjust the formatter parameter if you feel the display is too long)
%(levelno)s: prints the value of the log level
%(levelname)s: prints the log level name
%(pathname)s: prints the path of the currently executing program, which is actually [0].
%(filename)s: prints the name of the currently executing program
%(funcName)s: the current function for which the log is printed
%(lineno)d: prints the current line number of the journal
%(asctime)s: the time at which the log was printed
%(thread)d: prints the thread ID
%(threadName)s: prints the thread name
%(process)d: prints the process ID
%(message)s: prints a log message
Avoid the pitfalls: do not use this way to call the log level method will be printed in the log to locate the path error can only be located in the current method of the log wrapper class under the
def debug(self, message): self.__console('debug', message) def info(self, message): self.__console('info', message) def warning(self, message): self.__console('warning', message) def error(self, message): self.__console('error', message)
to this article on the python custom package with the color of the logging module is introduced to this article , more related python logging module content please search for my previous posts or continue to browse the following related articles I hope you will support me in the future !