python 封装logging
1 #!/usr/bin/python3 2 # -*- coding: utf-8 -*- 3 # @Time : 2020/9/25 9:55 4 # @Author : cheng 5 # @Email : 771535427@qq.com 6 # @File : log.py 7 # @Software: PyCharm 8 import logging 9 from logging.handlers import RotatingFileHandler 10 11 12 class BasicLog(object): 13 14 def __init__(self, level="INFO", filename="./log.txt", format="%(asctime)s - %(levelname)s - %(message)s"): 15 """ 16 封装logging日志类 17 :param level: 日志级别 [info, debug, warning, error, critical, fatal] 18 :param filename: 日志存储文件 19 :param format: 日志输出格式 20 """ 21 self._level = getattr(logging, level.upper()) 22 self._filename = filename 23 self._format = format 24 self._logger = logging.getLogger(__name__) 25 self._logger.setLevel(level=self._level) 26 self.init_logging() 27 28 def init_logging(self): 29 logging.basicConfig(level=self._level, filename=self._filename, format=self._format) 30 31 def info(self, message): 32 self._logger.info(message) 33 34 def debug(self, message): 35 self._logger.debug(message) 36 37 def warning(self, message): 38 self._logger.warning(message) 39 40 def error(self, message): 41 self._logger.error(message) 42 43 def critical(self, message): 44 self._logger.critical(message) 45 46 def fatal(self, message): 47 self._logger.fatal(message) 48 49 50 class RotatingLog(BasicLog): 51 def __init__(self, level, filename="./log.txt", 52 format="%(asctime)s - %(levelname)s - %(message)s", 53 maxBytes=(100 * 1024), 54 backupCount=3 55 ): 56 """ 57 封装logging日志回滚类 58 :param level: 日志级别 [info, debug, warning, error, critical, fatal] 59 :param filename: 日志存储文件 60 :param format: 日志输出格式 61 :param maxBytes: 单个日志文件大小 62 :param backupCount: 日志回滚数量 63 """ 64 self._maxBytes = maxBytes 65 self._backupCount = backupCount 66 super().__init__(level=level, filename=filename, format=format) 67 68 def init_logging(self): 69 rotatingHandler = RotatingFileHandler(filename=self._filename, maxBytes=self._maxBytes, 70 backupCount=self._backupCount) 71 72 rotatingHandler.setFormatter(logging.Formatter(self._format)) 73 74 self._logger.addHandler(rotatingHandler) 75 76 77 if __name__ == "__main__": 78 log = RotatingLog(level="debug") 79 log.info("Start print log") 80 log.debug("Do something") 81 log.warning("Something maybe fail.") 82 log.info("Finish")