从多个模块登录到同一日志文件

时间:2019-12-23 14:50:50

标签: python logging

我有一个简单的项目结构-我的主模块调用位于同一目录中的其他两个模块。我按照说明per this answer进行了设置。

我的代码如下:

主模块:

# log_test.py
import logging
import imported_1
import imported_2

def main():

    logger = logging.getLogger(__name__)
    logging.basicConfig(filename="test.log", format='%(asctime)s - %(name)s - %(levelname)s - %(message)s')
    logger.setLevel(logging.DEBUG)
    logger.debug("This is a debug message")
    logger.info("For your info")
    logger.warning("This is a warning message")
    logger.error("This is an error message")
    logger.critical("This is a critical message")

    imported_1.one_fn(5, 6)
    imported_2.two_fn(10, 20)

if __name__ == '__main__':
    main()

导入的模块-Imported_1.py

# imported_1.py
import logging
logger = logging.getLogger(__name__)

def one_fn(x, y):
    print(f"Logging function one with {x} and {y}")
    logger.info(f"Logging function one with {x} and {y}")

然后导入_2.py

# imported_2.py
import logging
logger = logging.getLogger(__name__)

def two_fn(x, y):
    print(f"Logging function two with {x} and {y}")
    logger.info(f"Logging function one with {x} and {y}")

生成的日志文件test.log仅包含来自主log_test.py模块的条目。导入的模块不在此处记录:

2019-12-21 18:26:41,351 - __main__ - DEBUG - This is a debug message
2019-12-21 18:26:41,351 - __main__ - INFO - For your info
2019-12-21 18:26:41,351 - __main__ - WARNING - This is a warning message
2019-12-21 18:26:41,351 - __main__ - ERROR - This is an error message

我正在寻找来自导入模块的日志消息,以显示在与basicConfig指定的日志文件相同的日志文件中。我在这里做什么错了?

1 个答案:

答案 0 :(得分:1)

为了使Imported1和Import2的记录器知道您创建的原始记录器,它们必须是其子记录。
在python中,记录器以'。'排列,因此记录器a.b.c是记录器a.b的子级,记录器alog_test.py的子级

您可以通过这种方式实现自己想要的:
logger = logging.getLogger('my_logger')

imported_1.py

logger = logging.getLogger('my_logger.' + __name__) # will be my_logger.imported_1

imported_2.py

logger = logging.getLogger('my_logger.' + __name__) # will be my_logger.imported_2

$ find . -type f -name '*.cpp' -exec sed -i -E 's#(^.*)(\/)([a-zA-Z0-9-]+\.h)#\#include "\3#g' {} \;

您可以在此处查看更多信息 https://docs.python.org/3/howto/logging-cookbook.html#using-logging-in-multiple-modules