In addition to Weibo, there is also WeChat
Please pay attention
WeChat public account
Shulou
2025-01-14 Update From: SLTechnology News&Howtos shulou NAV: SLTechnology News&Howtos > Development >
Share
Shulou(Shulou.com)06/01 Report--
In this article Xiaobian introduces in detail "how to customize the logging module with color in python", the content is detailed, the steps are clear, and the details are handled properly. I hope that this article "how to customize the logging module with color in python" can help you solve your doubts.
In the process of building a python interface automation framework to share some content, I want to encapsulate a logger method and repackage the code according to logging as follows
Import loggingimport osimport timeimport colorlogfrom logging.handlers import RotatingFileHandler# creates a file directory cur_path = os.path.dirname (os.path.realpath (_ _ file__)) # log_path is the path where logs are stored log_path = os.path.join (os.path.dirname (cur_path), 'logs') if not os.path.exists (log_path): os.mkdir (log_path) # if this logs folder does not exist Automatically create a # modify log save location timestamp = time.strftime ("% Y-%m-%d", time.localtime ()) logfile_name ='% s.log'% timestamplogfile_path = os.path.join (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 (logging.Logger): def _ _ init__ (self, name, level='DEBUG', file=None Encoding='utf-8'): super (). _ init__ (name) self.encoding = encoding self.file = file self.level = level # manually adjust the color for required log information formatter = colorlog.ColoredFormatter ('% (log_color) s% (levelname) 1.1 s% (asctime) s% (reset) s |% (message_log_color) s% ( Levelname)-8s% (reset) s |% (''log_color) s [% (filename) s% (reset) SV% (log_color) s% (module) s% (reset) SV% (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 Used to write to local rotatingFileHandler = logging.handlers.RotatingFileHandler (filename=logfile_path, maxBytes=1024 * 1024 * 50) BackupCount=5) rotatingFileHandler.setFormatter (formatter) rotatingFileHandler.setLevel (logging.DEBUG) self.addHandler (rotatingFileHandler) # create a StreamHandler For output to the console console = colorlog.StreamHandler () console.setLevel (logging.DEBUG) console.setFormatter (formatter) self.addHandler (console) self.setLevel (logging.DEBUG) logger = Logger (name=logfile_path, file=logfile_path)
When using it, we only need to introduce encapsulated classes to be intuitive, beautiful and generous.
# introduce encapsulated logger module from common.logger_handler import loggerdef physical_strength (self, abnormal): "General method for exchanging abnormal physical strength"if self.attrs.__contains__ ('costType'): attrs_Type = {" costType ": abnormal," count ": self.attrs [" count "]} response_Type = r (). Response (self.send_uid, self.code, self.event) Attrs_Type) # call logger.info () directly when using logger.info (f "physical_strength_ {abnormal}, response_Type: {response_Type}") assert response_Type ["code"]! = 0 time.sleep (2) attrs_count = {"costType": self.attrs ["costType"] "count": abnormal} response_count = r (). Response (self.send_uid, self.code, self.event, attrs_count) logger.info (f "physical_strength_ {abnormal}, response_count: {response_count}") assert response_count ["code"]! = 0 time.sleep (2) attrs_all = {"costType": abnormal "count": abnormal} response_all = r (). Response (self.send_uid, self.code, self.event, attrs_all) logger.info (f "physical_strength_ {abnormal} Response_all: {response_all} ") assert response_all [" code "]! = 0 time.sleep (2) else: attrs_count = {" count ": abnormal} response_count = r (). Response (self.send_uid, self.code, self.event, attrs_count) logger.info (f" physical_strength_ {abnormal}) Response_count: {response_count} ") assert response_count [" code "]! = 0 time.sleep (2)
Effect: displayed by date / time / log level / file name / class / method name / number of lines of code (here you can manually adjust the formatter parameters if the display is too long)
% (levelno) s: print log-level numeric values
% (levelname) s: print log level name
% (pathname) s: print the path of the currently executing program, which is actually sys.argv [0]
% (filename) s: print the name of the currently executing program
% (funcName) s: current function for printing logs
% (lineno) d: print the current line number of the log
% (asctime) s: time the log was printed
% (thread) d: print thread ID
% (threadName) s: print thread name
% (process) d: print process ID
% (message) s: print log information
Avoid the pit: do not call the log level method in this way, there will be a log print location path error can only be located under the current method of the log wrapper class
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). This article "how to customize the logging module with color in python" has been introduced. If you want to master the knowledge of this article, you still need to practice and use it. If you want to know more about the articles, you are welcome to follow the industry information channel.
Welcome to subscribe "Shulou Technology Information " to get latest news, interesting things and hot topics in the IT industry, and controls the hottest and latest Internet news, technology news and IT industry trends.
Views: 0
*The comments in the above article only represent the author's personal views and do not represent the views and positions of this website. If you have more insights, please feel free to contribute and share.
Continue with the installation of the previous hadoop.First, install zookooper1. Decompress zookoope
"Every 5-10 years, there's a rare product, a really special, very unusual product that's the most un
© 2024 shulou.com SLNews company. All rights reserved.