[英]Python - creating a logger if one doesn't exist
Often I will use a log in python with the following setup:通常我会在 python 中使用日志,设置如下:
logging.basicConfig(
format="(%(levelname)s) %(module)22s : %(message)s",
datefmt="%m/%d/%Y %I:%M:%S %p",
level=logging.INFO,
)
log = logging.getLogger(__name__)
Sometimes I have a module m.py
which can either be run by itself, or it can be called by another module.有时我有一个模块m.py
可以自己运行,也可以由另一个模块调用。
If the module m.py
is called as itself then I need all the setup outlined above, however, if m.py
is called by a different module then the above isn't necessary, I can just have如果模块m.py
本身被调用,那么我需要上面列出的所有设置,但是,如果m.py
由不同的模块调用,则不需要上述设置,我可以
log = logging.getLogger(__name__)
and it will inherit the logger that was created in the script that called m.py
.它将继承在名为m.py
的脚本中创建的记录器。
What I would like to know, is how to I have a setup which will take into account both of these scenarios for the script m.py
?我想知道的是,如何进行设置以考虑脚本m.py
的这两种情况?
If my understanding of your problem is correct, you can use the if (__name__ == "__main__"):
approach.如果我对您的问题的理解是正确的,您可以使用if (__name__ == "__main__"):
方法。
Here is a question highlighting how this works. 这是一个强调其工作原理的问题。
So, for your problem, you could do:因此,对于您的问题,您可以这样做:
if (__name__ == "__main__"):
logging.basicConfig(
format="(%(levelname)s) %(module)22s : %(message)s",
datefmt="%m/%d/%Y %I:%M:%S %p",
level=logging.INFO,
)
log = logging.getLogger(__name__)
This means the root configuration will run only if the module is called directly.这意味着只有在直接调用模块时才会运行根配置。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.