[英]Showing INFO-level python logs on stdout without changing source code
If a module whose source code I can't change says something like:如果我无法更改其源代码的模块显示如下:
# foo.py
import logging
logging.info('Hello world')
How can I see the logs while running运行时如何查看日志
$ python foo.py
from my POSIX-compliant terminal?从我的 POSIX 兼容终端?
All the answers I can find about this involve changing the source code.我能找到的所有答案都涉及更改源代码。
The docs are pretty clear about logging WARN-level and above: 文档非常清楚地记录了警告级别及以上:
The INFO message doesn't appear because the default level is WARNING. INFO 消息不会出现,因为默认级别是 WARNING。
But I can't easily see how to change that default.但我不能轻易看到如何更改该默认值。
Run the script with an incantation that preconfigures logging
for you (now 100% more Python3 compatible).使用为您预先配置logging
的咒语运行脚本(现在 100% 兼容 Python3)。
$ cat foo.py
import logging
logging.info('Hello world')
$ python3 -c 'import logging,sys,runpy;logging.basicConfig(level=logging.INFO,stream=sys.stdout);runpy.run_path("foo.py")'
INFO:root:Hello world
~/Desktop
To make it more memorable, you can wrap things in a please_log.py
.为了让它更令人难忘,您可以将内容包装在please_log.py
中。 Some sys.argv
finagling is required.需要一些sys.argv
修饰。
import logging, sys, runpy
script = sys.argv.pop(1)
logging.basicConfig(level=logging.INFO, stream=sys.stdout)
runpy.run_path(script)
import logging
import sys
logging.info('Hello world: %s', sys.argv)
$ python3 please_log.py foo.py
INFO:root:Hello world: ['foo.py']
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.