当前位置:主页 > 软件编程 > Python代码 >

python使用装饰器作日志处理的方法

时间:2021-01-14 11:15:51 | 栏目:Python代码 | 点击:

装饰器这东西我看了一会儿才明白,在函数外面套了一层函数,感觉和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'
```

您可能感兴趣的文章:

相关文章