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

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM