参考网址
www.coder.work/article/497…
前言
本文所依赖的库包是logging
demo
我有一个简单的项目结构: 我的主模块调用位于同一目录中的另外两个模块
主模块如下所示: 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()
导入的模块impoted_1:
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}")
导入的模块impoted_2:
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文件中。
从下面的日志可以看出来:日志文件中只有来自主模块中打印的日志,没有导入模块中打印的日志。
很明显,这不符合预期。
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
原因分析
为了使imported1 和import2 的记录器知道您创建的原始记录器,它们需要是它的子级。
在 python 中,记录器由 '.' 排列,因此记录器 `a.b.c`是 logger `a.b` 的 child 这是 `a` 的 child
你可以通过这种方式实现你想要的:
在 log_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
```