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

yipeiwu_com4年前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'
```

以上这篇python使用装饰器作日志处理的方法就是小编分享给大家的全部内容了,希望能给大家一个参考,也希望大家多多支持【听图阁-专注于Python设计】。

相关文章

Python Mysql数据库操作 Perl操作Mysql数据库

首先下载 MySQLdb #encoding=GBK import MySQLdb #import sys # #reload(sys) #sys.setdefaultencoding(...

python 实现读取一个excel多个sheet表并合并的方法

如下所示: import xlrd import pandas as pd from pandas import DataFrame DATA_DIR = 'E:/'...

python实现的登录和操作开心网脚本分享

SNS什么的我是一直无爱的,这次蛋疼写了个登录开心网(kaixin001)并向所有好友发送站内消息的脚本。 开心网在登录的时候做了一些处理,并不传原始密码,从js分析到的结果是:登录时会...

详解Python 实现元胞自动机中的生命游戏(Game of life)

详解Python 实现元胞自动机中的生命游戏(Game of life)

简介 细胞自动机(又称元胞自动机),名字虽然很深奥,但是它的行为却是非常美妙的。所有这些怎样实现的呢?我们可以把计算机中的宇宙想象成是一堆方格子构成的封闭空间,尺寸为N的空间就有NN个格...

Python中遍历字典过程中更改元素导致异常的解决方法

先来回顾一下Python中遍历字典的一些基本方法: 脚本: #!/usr/bin/python dict={"a":"apple","b":"banana","o":"orange...