当前位置:天才代写 > Python代写 > python 使用装饰器记录日志-python基础

python 使用装饰器记录日志-python基础

2021-02-14 17:40 星期日 所属: Python代写 浏览:9

装饰器

运用python装饰器纪录日志很便捷

编码:

#coding=utf8
import traceback
import logging
from logging.handlers import TimedRotatingFileHandler
def logger(func):
    def inner(*args, **kwargs): #1
        try:
            #print "Arguments were: %s, %s" % (args, kwargs)
            func(*args, **kwargs) #2
        except:
            #print 'error',traceback.format_exc()
            print 'error'
    return inner


def loggerInFile(filename):#带主要参数的装饰器必须2层装饰器完成,第一层传主要参数,第二层传涵数,各层涵数在上一层回到
    def decorator(func):
        def inner(*args, **kwargs): #1
            logFilePath = filename  # 日志按日期翻转,保存5天
            logger = logging.getLogger()
            logger.setLevel(logging.INFO)
            handler = TimedRotatingFileHandler(logFilePath,
                                               when="d",
                                               interval=1,
                                               backupCount=5)
            formatter = logging.Formatter('%(asctime)s  - %(levelname)s - %(message)s')
            handler.setFormatter(formatter)
            logger.addHandler(handler)
            try:
                #print "Arguments were: %s, %s" % (args, kwargs)
                result = func(*args, **kwargs) #2
                logger.info(result)
            except:
                logger.error(traceback.format_exc())
        return inner
    return decorator

@logger
def test():
    print 2/0

test()


@loggerInFile('newloglog')
def test2(n):
    print 100/n

test2(10)
test2(0)
print 'end'
 

    关键字:

天才代写-代写联系方式