class logit(object):
_logfile = 'out.log'
def __init__(self, func):
self.func = func
def __call__(self, *args):
log_string = self.func.__name__ + " was called"
print(log_string)
# 打开logfile并写入
with open(self._logfile, 'a') as opened_file:
# 现在将日志打到指定的文件
opened_file.write(log_string + '\n')
# 现在,发送一个通知
self.notify()
# return base func
return self.func(*args)
def notify(self):
# logit只打日志,不做别的
pass
logit._logfile = 'out2.log' # 如果需要修改log文件参数
@logit
def myfunc1():
pass
myfunc1()
# 输出: myfunc1 was called
class email_logit(logit):
'''
一个logit的实现版本,可以在函数调用时发送email给管理员
'''
def __init__(self, email='admin@myproject.com', *args, **kwargs):
self.email = email
super(email_logit, self).__init__(*args, **kwargs)
def notify(self):
# 发送一封email到self.email
# 这里就不做实现了
pass