最近我在写一个项目时遇到了一个需求:记录所有修改文件的操作类型和发生时间。折腾了好一会时间最终搞定,在此把折腾的过程记录下来分享给大家。
项目需求:
假设:项目中需要修改file1、file2时不得自行直接修改,必须调用file1、file2函数。在项目中有增加记录、修改记录、删除记录的操作,分别定义为append_file、edit_file、del_file,现在需要写日志,记录修改文件的操作类型、修改哪个文件、修改时间。
def file1(content):
pass # 把context写入file1
def file2(content):
pass # 把context写入file2
def append_file(content,file):
if file=='file1':
file1(content)
elif file=='file2':
file2(content)
def edit_file(content,file):
if file=='file1':
file1(content)
elif file=='file2':
file2(content)
def del_file(content,file):
if file=='file1':
file1(content)
elif file=='file2':
file2(content)
项目分析:
append_file、edit_file、del_file、file1、file2这些地方的代码内部不能改动,现在需要记录所有的文件修改的动作以及发生时间。最佳的解决方法是写一个装饰器,给file1()和file2()装饰,一旦它们被执行时就会写日志记录f“时间:{time},调用者:“{fun1}”调用了“{fun2}”。
难点分析:
import time
def log(func):
def inner(*args, **kwargs):
print(time.strftime)
print(func)
return func(*args, **kwargs)
return inner
@log
def file1(content):
pass # 把context写入file1
@log
def file2(content):
pass # 把context写入file2
def append_file(content,file):
if file=='file1':
file1(content)
elif file=='file2':
file2(content)
def edit_file(content,file):
if file=='file1':
file1(content)
elif file=='file2':
file2(content)
def del_file(content,file):
if file=='file1':
file1(content)
elif file=='file2':
file2(content)
可是我很快发现日志装饰器要记录时间和被调用者非常简单,一会写好了,可是怎么记录调用者呢??
我查阅了很多资料最终找到2种解决方案,顺带发现了一个小宝藏,嘿嘿。
解决方案1:
import time
import traceback
def log(func):
def inner(*args, **kwargs):
ret1 = time.strftime('%Y年%m月%d日%H时%M分%S秒')
ret2 = traceback.extract_stack()[-2][2]
ret3 = str(func).split(' ')[1]
print(f'时间:“{ret1}”,调用者:“{ret2}”,被调用者“{ret3}”')
return func(*args, **kwargs)
return inner
@log
def file1(content):
pass # 把context写入file1
@log
def file2(content):
pass # 把context写入file2
def append_file(content, file):
if file == 'file1':
file1(content)
elif file == 'file2':
file2(content)
def edit_file(content, file):
if file == 'file1':
file1(content)
elif file == 'file2':
file2(content)
def del_file(content, file):
if file == 'file1':
file1(content)
elif file == 'file2':
file2(content)
append_file('123', 'file1')
edit_file('456', 'file2')
del_file('789', 'file1')
out:
时间:“2020年11月21日20时13分26秒”,调用者:“append_file”,被调用者“file1”
时间:“2020年11月21日20时13分26秒”,调用者:“edit_file”,被调用者“file2”
时间:“2020年11月21日20时13分26秒”,调用者:“del_file”,被调用者“file1”
这里没啥特别值得分析的,记住import traceback,然后使用“traceback.extract_stack()[-2][2]”即可获得调用者的名字。
解决方案2:
装饰器内部ret2和解决方案1里面的内容不一样,但是返回结果一致。
import time
import inspect
def log(func):
def inner(*args, **kwargs):
ret1 = time.strftime('%Y年%m月%d日%H时%M分%S秒')
ret2 = inspect.stack()[1][3]
ret3 = str(func).split(' ')[1]
print(f'时间:“{ret1}”,调用者:“{ret2}”,被调用者“{ret3}”')
return func(*args, **kwargs)
return inner
out:
时间:“2020年11月21日20时13分26秒”,调用者:“append_file”,被调用者“file1”
时间:“2020年11月21日20时13分26秒”,调用者:“edit_file”,被调用者“file2”
时间:“2020年11月21日20时13分26秒”,调用者:“del_file”,被调用者“file1”
记住import inspect,然后使用“inspect.stack()[1][3]”即可获得调用者的名字。
探索inspect
import inspect
def log(func):
def inner(*args, **kwargs):
ret = inspect.stack()
for i in ret:
print('='*60)
for j in i:
print(j)
return func(*args, **kwargs)
return inner
@log
def file1(content):
pass
def append_file(content, file):
if file == 'file1':
file1(content)
append_file('123', 'file1')
out:
============================================================
<frame at 0x000002C8832909F0, file 'd:/Python/write.py', line 11, code inner>
d:/Python/write.py
7
inner
[' ret = inspect.stack()\n']
0
============================================================
<frame at 0x000002C882E1CA40, file 'd:/Python/write.py', line 23, code append_file>
d:/Python/write.py
23
append_file
[' file1(content)\n']
0
============================================================
<frame at 0x000002C882E1C440, file 'd:/Python/write.py', line 26, code <module>>
d:/Python自学笔记/函数/查找调用者/write.py
26
<module>
["append_file('123', 'file1')\n"]
0
在这里可以获取程序运行栈里的所有记录:
当前代码块:文件名、第几行代码、函数名、调用时执行的代码内容。
父级代码块:文件名、第几行代码、函数名、调用时执行的代码内容。
祖父代码块:文件名、第几行代码、函数名、调用时执行的代码内容。
……
这个在分析大型项目运行框架非常有帮助,必须mark一下,将来肯定用得上。