问题描述
我具有以下应用程序结构:
I have the following application structure:
./utils.py
def do_something(logger=None):
if not logger:
logger = logging.getLogger(__name__)
print('hello')
logger.debug('test')
./one.py
from utils import do_something
logger = logging.getLogger(__name__)
do_something(logger=logger)
./two.py
from utils import do_something
logger = logging.getLogger(__name__)
do_something(logger=logger)
现在,然后运行,记录输出将显示使用功能(one
和two
)而不是utils
的各个模块的名称.然后,我使用此信息(记录器的名称)来过滤消息.
Now, then this runs, the logging output will show the names of the respective modules that are using the functions (one
and two
) rather than utils
. I then use this information (the logger's name) to filter the messages.
有没有一种方法可以不必通过记录器作为参数来执行此操作?我是否必须基本内省调用方函数并基于该函数初始化记录器?如果在整个代码库中都使用一个函数,但记录器应该是那些调用该函数的记录器,那么对于这种类型的配方,通常的解决方案是什么?
Is there a way to do this without having to pass the logger though as an argument? Would I have to basically introspect the caller function and initialize a logger based on that? What's the common solution for this type of recipe, when one function is used all over the code base but the loggers should be of those calling the function?
推荐答案
变量logger
是全局变量,可以从这样的do_something()
函数内部进行访问:
Variable logger
being a global, can be accessed from inside do_something()
function like this:
logger = logging.getLogger(__name__)
def do_something():
x = logger
仔细阅读以下内容:
After reading this carefully:
在简单的英语为:
我断定别无选择!
在这种情况下,您必须将记录器作为参数传递.
I conclude that there is no other way!
You have to pass logger as an argument for this particular case.
from utils import do_something
logger = logging.getLogger(__name__)
do_something() # logger global is not visible in do_something()
do_something(logger=logger) # the only way
这篇关于在Python中记录为调用者模块的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!