码迷,mamicode.com
首页 > 编程语言 > 详细

python 通过装饰器实现类的日志记载

时间:2019-01-22 15:04:28      阅读:258      评论:0      收藏:0      [点我收藏+]

标签:efault   cname   formatter   装饰器   set   error   class   strftime   imp   

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 通过装饰器实现类的日志记载

标签:efault   cname   formatter   装饰器   set   error   class   strftime   imp   

原文地址:https://www.cnblogs.com/alplf123/p/10303667.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!