python 通过装饰器实现类的日志记载
Posted 我是外婆
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了python 通过装饰器实现类的日志记载相关的知识,希望对你有一定的参考价值。
import logging from logging import FileHandler, Formatter import os.path as fpath from datetime import datetime logfile = fpath.join(fpath.dirname(fpath.abspath(__file__)),datetime.now().strftime(‘%Y%m%d‘) + ‘.log‘) formatter = ‘%(asctime)s %(levelname)-8s %(name)-15s %(funcName)s %(message)s‘ dateformatter = ‘%Y-%m-%d %H:%M:%S‘ default_level = { ‘critical‘: 50, ‘error‘: 40, ‘warning‘: 30, ‘info‘: 20, ‘debug‘: 10 } def bindlog(level = ‘debug‘): def wrapper(cls): print(cls) logger = logging.getLogger(cls.__name__) logger.setLevel(default_level[level]) file_handle = FileHandler(logfile) file_handle.setFormatter(Formatter(formatter, dateformatter)) logger.addHandler(file_handle) def inner(*args, **kwargs): if not hasattr(cls, ‘log‘): setattr(cls, ‘log‘, logger) return(cls(*args, **kwargs)) return inner return wrapper @bindlog() class Test: def add(self): for _ in range(100): self.log.info(‘ceshi.‘)
以上是关于python 通过装饰器实现类的日志记载的主要内容,如果未能解决你的问题,请参考以下文章