[英]How do I use logfile created in Conftest.py in other files?
I have following setup 我有以下设置
../test/dirA
../test/Conftest.py
../test/Test_1.py
../test/logging.config
Code for Conftest.py Conftest.py的代码
import logging.config
from os import path
import time
config_file_path = path.join(path.dirname(path.abspath(__file__)), 'logging.conf')
log_file_path = path.join(path.dirname(path.abspath(__file__)), ‘logFile.log’)
logging.config.fileConfig(config_file_path)
logger = logging.getLogger(__name__)
fh = logging.FileHandler(log_file_path)
fh.setLevel(logging.DEBUG)
ch = logging.StreamHandler()
ch.setLevel(logging.ERROR)
# add the handlers to the logger
logger.addHandler(fh)
logger.addHandler(ch)
logging.info('done')
Code for ../test/Test_1.py 代码为../test/Test_1.py
import logging
logger = logging.getLogger(__name__)
def test_foo():
logger = logging.getLogger(__name__)
logger.info("testing foo")
def test_foobar():
logger = logging.getLogger(__name__)
logger.info("testing foobar")
I need to see logs from both files in logFile.log but currently I see only log from conftest.py. 我需要在logFile.log中查看来自这两个文件的日志,但目前我只看到来自conftest.py的日志。 What am I missing?
我错过了什么?
Also, I noticed that if I execute Conftest.py from test folder (one dir up), for some reason it does not see logging.config. 另外,我注意到如果我从测试文件夹(一个目录)执行Conftest.py,由于某种原因它没有看到logging.config。
Is my usage for conftest for correct for logging? 我对conftest的使用是否正确用于记录? How else I can achieve same result?
我怎么能达到同样的效果呢?
Thank you 谢谢
Update: I used approach described 更新:我使用了描述的方法
With some changes, this addresses my question. 通过一些更改,这解决了我的问题。 Another lesson I learned that use
我学到了另一个教训
logging.getLogger(__name__)
at function level, not at module level. 在功能级别,而不是在模块级别。 You can see a lots of example out there (including this article, I did it just for giving example in short) get logger at module level.
你可以在那里看到很多例子(包括这篇文章,我只是为了举例说明),在模块级别获取logger。 They looks harmless, but actually, there is a pitfall – Python logging module respects all created logger before you load the configuration from a file, if you get logger at the module level like this
它们看起来无害,但实际上,存在一个陷阱 - 如果你在模块级别获得这样的记录器,Python日志模块会在从文件加载配置之前尊重所有创建的记录器
Well, my first guess is that if you don't import the Conftest.py in the test_1.py, the logger setup code is not reached and executed, so the logging in the Test_1 file is in a default location log file. 好吧,我的第一个猜测是,如果你没有在test_1.py中导入Conftest.py,则不会到达并执行记录器设置代码,因此Test_1文件中的日志记录位于默认位置日志文件中。
Try this line to find the location of the log file: 尝试以下行来查找日志文件的位置:
logging.getLoggerClass().root.handlers[0].baseFilename
I used approach described at https://blog.muya.co.ke/configuring-multiple-loggers-python/ . 我使用了https://blog.muya.co.ke/configuring-multiple-loggers-python/中描述的方法。
With some changes, this addresses my question. 通过一些更改,这解决了我的问题。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.