【发布时间】:2017-07-28 00:32:04
【问题描述】:
我正在编写一个具有日志记录功能的 python 脚本。我已经阅读了 logging 模块的文档以及许多 Stack Overflow 帖子,我学到了很多东西,但我仍然无法理解 logging 模块如何允许不同的模块将日志事件发送到相同的目的地。
我的主模块使用了我在网上找到的 python 模块。该模块已经设置了日志记录以写入日志文件,但我希望它写入我在主模块中定义的日志文件。
#myModule.py
import logging
import otherModule
logger = logging.getLogger(__name__)
if __name__ == "__main__":
logger.setLevel(logging.DEBUG)
handler = logging.FileHandler('my_log.log')
handler.setLevel(logging.DEBUG)
formatter = logging.Formatter('[%(asctime)s] %(levelname)%s: %(message)s')
handler.setFormatter(formatter)
logger.addHandler(handler)
def main():
logger.info('hello world')
otherModule.do_stuff()
如您所见,我明确设置了我的处理程序和格式化程序,然后将它们添加到我的记录器实例中。但这就是我正在使用的模块的日志设置方式:
#otherModule.py
import logging
logging.basicConfig(filename='otherModule.log', filemode='w')
def do_stuff():
logging.info('Stuff is happening')
有了这个设置,我有两个问题:
- 我们设置日志记录的方式有什么不同?起初我尝试使用
logging.basicConfig(),但我无法让它写入日志文件(我可能做错了什么)。但我想知道创建日志实例 (logger = logging.getLogger(__name__)) 和直接调用日志函数 (logging.info(msg)) 之间的区别。 - 如何让
otherModule.py写入主模块中定义的同一个日志文件,Python 如何知道使用在myModule.py中创建的记录器(我试图通过查看来找出答案Python 文档,但他们大多只是说您可以跨多个模块登录到同一个地方)?由于它是一个开源模块,我宁愿不要修改它以供自己使用。
【问题讨论】:
标签: python python-3.x logging module