如何在其他文件中使用在Conftest.py中创建的日志文件?

时间:2019-05-07 15:38:04

标签: python logging

我有以下设置

../test/dirA
../test/Conftest.py
../test/Test_1.py
../test/logging.config

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')

../ 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")

我需要从logFile.log中的两个文件中查看日志,但是目前我仅从conftest.py中看到日志。我想念什么?

此外,我注意到,如果我从测试文件夹(一个目录上)执行Conftest.py,由于某种原因,它将看不到logging.config。

我的conftest用法是否正确记录日志? 我还能如何取得相同的结果?

谢谢

更新: 我用描述的方法

  1. https://blog.muya.co.ke/configuring-multiple-loggers-python/
  2. https://fangpenlin.com/posts/2012/08/26/good-logging-practice-in-python/

进行一些更改后,这解决了我的问题。 我学到的另一课是

 logging.getLogger(__name__)

在功能级别,而不是模块级别。 您可以在其中看到很多示例(包括本文,我只是为了给出示例而这样做),使logger处于模块级别。它们看起来无害,但实际上存在一个陷阱–如果从这样的模块级别获取记录器,则从文件加载配置之前,Python记录模块会尊重所有已创建的记录器

2 个答案:

答案 0 :(得分:0)

好吧,我的第一个猜测是,如果不将Conftest.py导入到test_1.py中,则不会到达并执行记录器设置代码,因此Test_1文件中的记录位于默认位置的日志文件中。

尝试以下行以查找日志文件的位置:

logging.getLoggerClass().root.handlers[0].baseFilename

答案 1 :(得分:0)

我使用了https://blog.muya.co.ke/configuring-multiple-loggers-python/中描述的方法。

进行一些更改,可以解决我的问题。

相关问题