装饰器

利用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'