kuz*_*roo 4 python logging arguments function
我发现自己多次编写这样的代码:
def my_func(a, b, *args, **kwargs):
saved_args = locals() # Learned about this from http://stackoverflow.com/a/3137022/2829764
local_var = "This is some other local var that I don't want to log"
try:
a/b
except Exception as e:
logging.exception("Oh no! My args were: " + str(saved_args))
raise
Run Code Online (Sandbox Code Playgroud)
运行my_func(1, 0, "spam", "ham", my_kwarg="eggs")在 stderr 上给出以下输出:
ERROR:root:Oh no! My args were: {'a': 1, 'args': (u'spam', u'ham'), 'b': 0, 'kwargs': {'my_kwarg': u'eggs'}}
Traceback (most recent call last):
File "/Users/kuzzooroo/Desktop/question.py", line 17, in my_func
a/b
ZeroDivisionError: division by zero
Run Code Online (Sandbox Code Playgroud)
我的问题是,我可以编写一些可重用的东西,这样我就不必在函数顶部保存 locals() 吗?它能以一种很好的 Pythonic 方式完成吗?
编辑:响应@mtik00的另一个请求:理想情况下,我想要某种方式从my_func中访问saved_args等,以便我可以做一些除了记录未捕获的异常之外的事情(也许我想捕获my_func中的异常,log错误,然后继续)。
装饰器就是您正在寻找的。这是一个例子:
import logging
from functools import wraps
def arg_logger(func):
@wraps(func)
def new_func(*args, **kwargs):
saved_args = locals()
try:
return func(*args, **kwargs)
except:
logging.exception("Oh no! My args were: " + str(saved_args))
raise
return new_func
@arg_logger
def func(arg1, arg2):
return 1 / 0
if __name__ == '__main__':
func(1, 2)
Run Code Online (Sandbox Code Playgroud)
在这里,我使用 arg_logger() 作为装饰器。将装饰器应用到您想要具有此新行为的任何函数。
这里有关于装饰器的很好的讨论。
| 归档时间: |
|
| 查看次数: |
3327 次 |
| 最近记录: |