python之装饰器进阶——记录日志:时间、调用者、被调用者

最近我在写一个项目时遇到了一个需求:记录所有修改文件的操作类型和发生时间。折腾了好一会时间最终搞定,在此把折腾的过程记录下来分享给大家。

项目需求:

假设:项目中需要修改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:
时间:“20201121201326秒”,调用者:“append_file”,被调用者“file1”
时间:“20201121201326秒”,调用者:“edit_file”,被调用者“file2”
时间:“20201121201326秒”,调用者:“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:
时间:“20201121201326秒”,调用者:“append_file”,被调用者“file1”
时间:“20201121201326秒”,调用者:“edit_file”,被调用者“file2”
时间:“20201121201326秒”,调用者:“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一下,将来肯定用得上。

  • 1
    点赞
  • 6
    收藏
    觉得还不错? 一键收藏
  • 1
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值