Python 如何正确地编写函数调用日志装饰程序?
举个例子: debug.py:Python 如何正确地编写函数调用日志装饰程序?,python,Python,举个例子: debug.py: import logging class log_funcname: def __init__(self, the_logger): self.the_logger = the_logger def __call__(self, fn): def simply_call(*args, **kwargs): self.the_logger.critical(fn.func_name)
import logging
class log_funcname:
def __init__(self, the_logger):
self.the_logger = the_logger
def __call__(self, fn):
def simply_call(*args, **kwargs):
self.the_logger.critical(fn.func_name)
return fn(*args, **kwargs)
return simply_call
logger = logging.getLogger()
formatter = logging.Formatter("%(lineno)s")
ch = logging.StreamHandler()
ch.setFormatter(formatter)
logger.addHandler(ch)
@log_funcname(logger)
def hello():
pass
hello()
输出:
$ python debug.py
10
我的意思是创建一个调用记录器的函数,将实际执行的行号和文件名传递给记录器。如果我希望示例应用程序输出25而不是10,那么我应该更改什么 可能重复,但使用inspect.currentframe有一个解决方案:我知道行号在某种程度上是你问题的核心,但通过添加这样的行号,你会让其他人更难测试你的代码。另请参阅右图,使用模块检查,您将找到所有内容there@Martijn皮特斯:为什么会变得更难?