装饰器这东西我看了一会儿才明白,在函数外面套了一层函数,感觉和java里的aop功能很像;写了2个装饰器日志的例子,
第一个是不带参数的装饰器用法示例,功能相当于给函数包了层异常处理,第二个是带参数的装饰器用法示例,将日志输出到文件。
```
#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'
```
以上这篇python使用装饰器作日志处理的方法就是小编分享给大家的全部内容了,希望能给大家一个参考,也希望大家多多支持我们。
时间: 2019-07-09