Network Security Internet Technology Development Database Servers Mobile Phone Android Software Apple Software Computer Software News IT Information

In addition to Weibo, there is also WeChat

Please pay attention

WeChat public account

Shulou

What is the Python Log file size setting and backup method?

2025-01-19 Update From: SLTechnology News&Howtos shulou NAV: SLTechnology News&Howtos > Development >

Share

Shulou(Shulou.com)06/02 Report--

This article introduces the relevant knowledge of "what is the Python Log file size setting and backup method". In the operation of the actual case, many people will encounter such a dilemma, so let the editor lead you to learn how to deal with these situations. I hope you can read it carefully and be able to achieve something!

I. size and number of configuration files

The log file code needs to introduce the RotatingFileHandler method, as follows:

From logging.handlers import RotatingFileHandler

Configure the size and number of files, such as: "set to write to a file. If the file is larger than 1m, cut the log file and keep only 3 files", as shown below:

# write to the file. If the file is larger than 1m, cut the log file, leaving only 3 files logger_handler = RotatingFileHandler (filename=log_path, maxBytes=1 * 1024 * 1024, backupCount=3, encoding='utf-8')

If the file size exceeds 1m, cut the log file, leaving only 3 files, and the file format is app.log1 and app.log2..., as shown in the figure:

The source code of the RotatingFileHandler method is as follows:

II. Log code #! / usr/bin/env python#-*-coding:utf-8-*-""-# @ FileName: handle_log.py# @ Time: 2020-8-31 19 FileName @ Author: xieyuanzuo# @ description:- -"" import loggingimport osimport colorlogfrom logging.handlers import RotatingFileHandlerfrom datetime import datetimecur_path = os.path.dirname (os.path.realpath (_ _ file__)) # current project path log_path = os.path.join (os.path.dirname (cur_path)) 'logs') # log_path is the path where logs are stored: if not os.path.exists (log_path): os.mkdir (log_path) # if there is no logs folder Then automatically create log_colors_config = {# Terminal output log color configuration 'DEBUG':' white', 'INFO':' cyan', 'WARNING':' yellow', 'ERROR':' red', 'CRITICAL':' bold_red' } default_formats = {# Terminal output format 'color_format':'% (log_color) s% (asctime) s% (name) s% (filename) s-[line:% (lineno) d] -% (levelname) s-[log information]:% (message) s' # Log output format 'log_format':'% (asctime) s muri% (name) s mure% (filename) s-[line:% (lineno) d] -% (levelname) s-[log information]:% (message) s'} class HandleLog: "" create a logger (logging.getLogger) first Then set the log level (logger.setLevel), then create the log file, where the log is saved (logging.FileHandler), and then set the log format (logging.Formatter) Finally, record the log handler to the logger (addHandler) "" def _ _ init__ (self): self.__now_time = datetime.now (). Strftime ('% Ymurt% mmure% d') # current date format self.__all_log_path = os.path.join (log_path) Self.__now_time + "- all" + ".log") # collect all log information file self.__error_log_path = os.path.join (log_path Self.__now_time + "- error" + ".log") # collect error log information file self.__logger = logging.getLogger () # create logger self.__logger.setLevel (logging.DEBUG) # set default logger recording level @ staticmethod def _ _ init_logger_handler (log_path): "" create logger handler Used to collect logs: param log_path: log file path: return: logger "" # write to the file, if the file is larger than 1m, cut the log file Keep only 3 files logger_handler = RotatingFileHandler (filename=log_path, maxBytes=1 * 1024 * 1024, backupCount=3, encoding='utf-8') return logger_handler @ staticmethod def _ _ init_console_handle (): "" create terminal logger handler Used to output to the console "" console_handle = colorlog.StreamHandler () return console_handle def _ _ set_log_handler (self, logger_handler Level=logging.DEBUG): "" set the handler level and add to the logger collector: param logger_handler: logger: param level: logger level "logger_handler.setLevel (level=level) self.__logger.addHandler (logger_handler) def _ _ set_color_handle (self Console_handle): "" set the handler level and add to the terminal logger collector: param console_handle: terminal logger: param level: logger level "console_handle.setLevel (logging.DEBUG) self.__logger.addHandler (console_handle) @ staticmethod def _ _ set_color_formatter (console_handle)" Color_config): "" set output format-console: param console_handle: terminal logger: param color_config: console print color configuration information: return: "" formatter = colorlog.ColoredFormatter (default_formats ["color_format"] Log_colors=color_config) console_handle.setFormatter (formatter) @ staticmethod def _ _ set_log_formatter (file_handler): "set log output format-log file: param file_handler: logger" formatter = logging.Formatter (default_formats ["log_format"], datefmt='%a % d% b% Y% HGV% MVA% S') file_handler.setFormatter (formatter) @ staticmethod def _ close_handler (file_handler): "close handler: param file_handler: logger" file_handler.close () def _ console (self, level Message): "construct log collector"all_logger_handler = self.__init_logger_handler (self.__all_log_path) # create log file error_logger_handler = self.__init_logger_handler (self.__error_log_path) console_handle = self.__init_console_handle () self.__set_log_ Formatter (all_logger_handler) # set the log format self.__set_log_formatter (error_logger_handler) self.__set_color_formatter (console_handle Log_colors_config) self.__set_log_handler (all_logger_handler) # set the handler level and add to the logger collector self.__set_log_handler (error_logger_handler Level=logging.ERROR) self.__set_color_handle (console_handle) if level= = 'info': self.__logger.info (message) elif level= =' debug': self.__logger.debug (message) elif level= = 'warning': self.__logger.warning (message) elif level= =' error': Self.__logger.error (message) elif level = 'critical': self.__logger.critical (message) self.__logger.removeHandler (all_logger_handler) # avoid duplicate log output problems self.__logger.removeHandler (error_logger_handler) self.__logger.removeHandler (console_handle) self.__close_handler (all_logger_handler) # close handler self.__close_handler (error_logger_handler) 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) def critical (self, message): self.__console ('critical') Message) log = HandleLog () if _ _ name__ ='_ _ main__': for i in range (50000): log.info ("this is a log message") log.debug ("this is a debug message") log.warning ("this is a warning message") log.error ("this is an error log message") log.critical ("this is a severity level message") This is the end of the content of "what is the Python Log file size setting and backup method"? Thank you for your reading. If you want to know more about the industry, you can follow the website, the editor will output more high-quality practical articles for you!

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.

Share To

Development

Wechat

© 2024 shulou.com SLNews company. All rights reserved.

12
Report