gpt4 book ai didi

python - 登录模块 - Python

转载 作者:太空宇宙 更新时间:2023-11-03 21:29:49 26 4
gpt4 key购买 nike

在 MAIN_SETUP.py 程序中,我导入 otherMod2

MAIN_SETUP.py

import logging
import otherMod2


# ----------------------------------------------------------------------
def main():
"""
The main entry point of the application
"""
logger = logging.getLogger("exampleApp")
logger.setLevel(logging.INFO)

# create the logging file handler
fh = logging.FileHandler("new_snake.log")

formatter = logging.Formatter('%(asctime)s - %(name)s - %(levelname)s - %(message)s')
fh.setFormatter(formatter)

# add handler to logger object
logger.addHandler(fh)

logger.info("Program started")
result = otherMod2.add(7, 8)
logger.info("Done!")


if __name__ == "__main__":
main()

otherMod2.py

import logging

module_logger = logging.getLogger("exampleApp.otherMod2")


# ----------------------------------------------------------------------
def add(x, y):
""""""
logger = logging.getLogger("exampleApp.otherMod2.add")
logger.info("added %s and %s to get %s" % (x, y, x + y))
return x + y

如果我运行程序(MAIN_SETUP.py),则会创建 new_snake.log 文件,以下数据将写入该文件

2018-12-03 16:21:29,772 - exampleApp - INFO - Program started
2018-12-03 16:21:29,772 - exampleApp.otherMod2.add - INFO - added 7 and 8 to get 15
2018-12-03 16:21:29,772 - exampleApp - INFO - Done!

问题 1:

在 otherMod2.py 中,我们确实有以下记录器,它只是定义并没有使用。我们可以删除它吗?如果删除的话会有影响吗?

module_logger = logging.getLogger("exampleApp.otherMod2")

问题2:

在 otherMod2.py 中没有为下面的记录器定义处理程序,但仍然在 new_snake.log 文件中写入,这是怎么可能的

logger = logging.getLogger("exampleApp.otherMod2.add")
logger.info("added %s and %s to get %s" % (x, y, x + y))

最佳答案

回答这两个问题:

问题1

您可以删除模块级记录器 exampleApp.otherMod2但是,您可能希望保留它,以便模块中的其他代码可以使用它。

创建模块级记录器是 recommended approach - 通常通过调用 logger.getLogger(__name__) 。这将使用与模块的包结构相同的层次结构来设置记录器。

问题2

Python 记录器是在由记录器名称中的点确定的层次结构中构建的。默认情况下,记录在层次结构较低位置的事件也会传递到层次结构较高位置的记录器。

所以虽然你的 exampleApp.otherMod2.add logger没有处理程序,事件被传递到顶层exampleApp logger 将其输出到日志文件。

此行为由 propagate 控制属性。您可以将其设置为 False以便更高级别的记录器不会收到事件。

logger = logging.getLogger("exampleApp.otherMod2.add")
logger.propagate = False
logger.info("added %s and %s to get %s" % (x, y, x + y))

在这种情况下,您需要将处理程序附加到 exampleApp.otherMod2.add如果你想让它输出任何东西。

关于python - 登录模块 - Python,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53592577/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com