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.')