python 装饰器小技巧(2) 给类添加日志输出

import logging
#创建日志文件
file = './test123.log'
logger = logging.getLogger('test')

#设置日志等级
logger.setLevel(logging.INFO)

#添加文件输出流
filehanle = logging.FileHandler(file, mode='a')

#设置日志输出格式
formatter = logging.Formatter('%(asctime)s - %(name)s - %(levelname)s - %(message)s')
filehanle.setLevel(logging.INFO)
filehanle.setFormatter(formatter)

#添加文件流到logger
logger.addHandler(filehanle)

#创建类装饰器
def loghandle(cls):
    if not hasattr(cls, 'log'):
        setattr(cls, 'log', logger)
    return cls
@loghandle
class Test:
    def func(self):
        self.log.warning('hsdfsdf')
        self.log.info('this is info msg')
t = Test()
t.func()
原文地址:https://www.cnblogs.com/alplf123/p/8961502.html