我在使用 python 的日志记录时遇到了一些困难。我有两个文件,main.py 和 mymodule.py。通常运行 main.py,它会导入 mymodule.py 并使用那里的一些函数。但有时,我会直接运行 mymodule.py。
我试图让它只在 1 个位置配置日志记录,但似乎有些错误。
这是代码。
# main.py
import logging
import mymodule
logger = logging.getLogger(__name__)
def setup_logging():
# only cofnigure logger if script is main module
# configuring logger in multiple places is bad
# only top-level module should configure logger
if not len(logger.handlers):
logger.setLevel(logging.DEBUG)
# create console handler with a higher log level
ch = logging.StreamHandler()
ch.setLevel(logging.DEBUG)
formatter = logging.Formatter('%(levelname)s: %(asctime)s %(funcName)s(%(lineno)d) -- %(message)s', datefmt = '%Y-%m-%d %H:%M:%S')
ch.setFormatter(formatter)
logger.addHandler(ch)
if __name__ == '__main__':
setup_logging()
logger.info('calling mymodule.myfunc()')
mymodule.myfunc()
Run Code Online (Sandbox Code Playgroud)
和导入的模块:
# mymodule.py
import logging
logger = logging.getLogger(__name__)
def myfunc():
msg = 'myfunc is being called'
logger.info(msg)
print('done with myfunc')
if __name__ == '__main__':
# only cofnigure logger if script is main module
# configuring logger in multiple places is bad
# only top-level module should configure logger
if not len(logger.handlers):
logger.setLevel(logging.DEBUG)
# create console handler with a higher log level
ch = logging.StreamHandler()
ch.setLevel(logging.DEBUG)
formatter = logging.Formatter('%(levelname)s: %(asctime)s %(funcName)s(%(lineno)d) -- %(message)s', datefmt = '%Y-%m-%d %H:%M:%S')
ch.setFormatter(formatter)
logger.addHandler(ch)
logger.info('myfunc was executed directly')
myfunc()
Run Code Online (Sandbox Code Playgroud)
当我运行代码时,我看到了这个输出:
$>python main.py
INFO: 2016-07-14 18:13:04 <module>(22) -- calling mymodule.myfunc()
done with myfunc
Run Code Online (Sandbox Code Playgroud)
但我希望看到这一点:
$>python main.py
INFO: 2016-07-14 18:13:04 <module>(22) -- calling mymodule.myfunc()
INFO: 2016-07-14 18:15:09 myfunc(8) -- myfunc is being called
done with myfunc
Run Code Online (Sandbox Code Playgroud)
有人知道为什么第二个 logging.info 调用没有打印到屏幕上吗?提前致谢!
记录器存在于层次结构中,根记录器(使用 检索logging.getLogger()
,无参数)位于顶部。每个记录器都从其父记录器继承配置,记录器本身的任何配置都会覆盖继承的配置。在这种情况下,您永远不会配置根记录器,而仅配置main.py
. 因此,mymodule.py
永远不会配置特定于模块的记录器。
最简单的修复可能是使用logging.basicConfig
in来设置您希望所有main.py
记录器共享的选项。
切普纳是正确的。我陷入了这个问题。问题出在你的主脚本中
16 log = logging.getLogger() # use this form to initialize the root logger
17 #log = logging.getLogger(__name__) # never use this one
Run Code Online (Sandbox Code Playgroud)
如果您使用第 17 行,那么您导入的 python 模块将不会记录任何消息
在你的 submodule.py 中
import logging
logger = logging.getLogger()
logger.debug("You will not see this message if you use line 17 in main")
Run Code Online (Sandbox Code Playgroud)
希望这篇文章可以帮助那些陷入这个问题的人。
归档时间: |
|
查看次数: |
4765 次 |
最近记录: |