代碼示例
# -*- coding:utf-8 -*-
from functools import wraps
from datetime import datetime
#類的裝飾器寫法著隆,日志
class log(object):
def __init__(self, logfile='c:\out.log'):
self.logfile = logfile
def __call__(self, func):
@wraps(func)
def wrapped_func(*args, **kwargs):
self.writeLog(*args, **kwargs) # 先調(diào)用 寫入日志
return func(*args, **kwargs) # 正式調(diào)用主要處理函數(shù)
return wrapped_func
#寫入日志
def writeLog(self, *args, **kwargs):
time = datetime.now().strftime("%Y-%m-%d %H:%M:%S")
log_str = time+' 操作人:{0[0]} 進行了【{0[1]}】操作'.format(args)
with open(self.logfile, 'a',encoding='utf8') as file:
file.write(log_str + '\n')
@log()
def myfunc(name,age):
print('姓名:{0},年齡:{1}'.format(name,age))
if __name__ == '__main__':
myfunc('小白', '查詢')
myfunc('root', '添加人員')
myfunc('小小', '修改數(shù)據(jù)')
日志己保存于指定位置,打開內(nèi)容如下:
最后編輯于 :
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請聯(lián)系作者