logging我为我称为 的模块编写了一个自定义日志记录类call。对于这个类,我希望将其放置在任何函数/方法中,并记录函数名称及其参数以及调用函数时使用的所有值。
这对于类方法来说效果很好
Foo.bar(self, a=1, b=2, c=3, *args=(), **kwargs={'something': 4})
Run Code Online (Sandbox Code Playgroud)
使用这个最小的例子
import logging
import inspect
def call(logger):
fname = [] # Function name including module and class
fargs = [] # Arguments of function including positional and named arguments
parentframe = inspect.stack()[1][0]
module = inspect.getmodule(parentframe)
if module and module.__name__ != "__main__":
fname.append(module.__name__)
codename = parentframe.f_code.co_name
if "self" in parentframe.f_locals:
fname.append(parentframe.f_locals["self"].__class__.__name__)
fobj = getattr(parentframe.f_locals["self"].__class__, codename)
if codename != "<module>":
fname.append(codename)
argspec = inspect.formatargspec(*inspect.getfullargspec(fobj))
args = argspec[1:-1].split(",")
for arg …Run Code Online (Sandbox Code Playgroud) python-3.x ×1