【问题标题】:Decorator that logs information to a file in Python将信息记录到 Python 文件中的装饰器
【发布时间】:2022-12-01 01:05:10
【问题描述】:
我的任务是:编写一个装饰器,记录有关装饰函数的调用、其参数值、关键字参数和执行时间的信息。日志应写入文件。
**使用示例
**
@日志
def foo(a, b, c):
...
foo(1, 2, c=3)
日志.txt...
富;参数:a=1,b=2; kwargs: c=3;执行时间:0.12 秒。
...
你能帮我吗?
【问题讨论】:
标签:
python
python-3.x
logging
decorator
【解决方案1】:
尝试这个
from time import time
def log(func):
def wrapper(*args, **kwargs):
start_time = time()
func(*args, **kwargs)
end_time = time() - start_time
args_names = func.__code__.co_varnames[:func.__code__.co_argcount]
args_names ={**dict(zip(args_names, args))}
with open('log.txt', 'a+') as file:
file.write(f'{func.__name__}, args={args_names}, kwargs={kwargs}, {end_time}
')
return wrapper
@log
def some_fun(a, b, c):
pass
some_fun(5, 10, c=15)