建立基本日誌類:網絡
import logging from logging import handlers FORMAT = '%(acstime)s - %(pathname)s[line:%(lineno)d] - %(levelname)s - %(message)s' # 設置日誌格式 class Logger(object): # 日誌級別關係映射 kv = { 'debug': logging.DEBUG, 'info': logging.INFO, 'warning': logging.WARNING, 'error': logging.ERROR, 'crit': logging.CRITICAL } def __init(self, filename, level='info', when='D', backcount=3, fmt=FORMAT): """ :param filename: 寫入日誌的文件名 :param level: 日誌級別 :param when: 日誌切分週期 :param backcount: 每完成一個週期的日誌寫入文件,最多保留的 日誌文件數,舊的日誌文件將被刪除 :param fmt: 日誌格式 """ self.logger = logging.getLogger(filename) fmt_str = logging.Formatter(fmt) # 日誌格式 self.logger.setLevel(self.kv.get(level)) # 日誌級別 sh = logging.StreamHandler() # 輸出到控制檯 sh.setFormatter(fmt_str) # 日誌在控制檯的輸出格式 th = handlers.TimedRotatingFileHandler(filename, when=when, backupCount=backupcount, encoding='utf-8') th.setFormatter(fmt_str) self.logger.addHandler(sh) self.logger.addHandler(th)
建立log對象,日誌級別爲'DEBUG'及以上的寫入日誌文件:debug
log = Logger(filename='all.log', level='debug').logger
建立Student類,屬性score只能爲整數類型:日誌
class Student(object): def __init__(self, name, id): self.name = name self.id = id log.info(f'{student name:{name}, id:{id}}') @property def score(self): return self.__score @score.setter def score(self, score): if isinstance(score, int) self.__score = score log.info(f'{student {name} got {self.score}}') else: log.error(f'學生分數類型錯誤,應該爲整型!') raise TypeError(f'學生分數類型錯誤,應該爲整型!')
實例化Student類:code
xiaoming = Student(10086, 'xiaoming') xiaoming.score = 90 xiaohong = Student(10010, 'xiaohong') xiaohong.score = 90.6
整理自網絡,侵刪。orm