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()

 

posted @ 2018-04-27 11:21  我是外婆  阅读(1331)  评论(0编辑  收藏  举报