python日志装饰器实现

时间:2021-11-16 22:26:26

问题出自:https://www.liaoxuefeng.com/wiki/0014316089557264a6b348958f449949df42a6d3a2e542c000/0014318435599930270c0381a3b44db991cd6d858064ac0000#0

再思考一下能否写出一个@log的decorator,使它既支持:

@log
def f():
    pass
又支持:

@log('execute')
def f():
    pass

  

贴上我的实现代码:

import functools


def log(param):
if callable(param):
def wrapper(*args, **kw):
print('%s function()' % (param.__name__,))
param(*args, **kw)

return wrapper

def decorator(func):
@functools.wraps(func)
def wrapper(*args, **kw):
print('%s %s():' % (param, func.__name__))
return func(*args, **kw)

return wrapper

return decorator


@log
def now():
print("2018")


@log("测试")
def now2():
print("2018")


now()
now2()

输出:
now function()
2018
测试 now2():
2018

  

亲测可行