在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中,我们确实在logger下面,它只是定义的而不是使用的。我们可以删除它吗?如果我们删除它会产生任何影响。
module_logger = logging.getLogger("exampleApp.otherMod2")
问题2:
在otherMod2.py中没有为logger下方定义处理程序,但仍将其写入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
记录器没有处理程序,但该事件将传递到顶级exampleApp
记录器,并将其输出到日志文件。
此行为由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
上附加一个处理程序。