k8s pod log日志不显示python print打印的内容

发布时间 2023-03-30 11:52:03作者: 徐风吟

问题

Python 程序代码中使用 print() 打印的内容,在查询 k8s pod 日志时不显示。

原因

Python 的 print() 函数签名如下:

print(*objects, sep=' ', end='\n', file=None, flush=False)

摘录部分官方文档如下:

The file argument must be an object with a write(string) method; if it is not present or None, sys.stdout will be used. Since printed arguments are converted to text strings, print() cannot be used with binary mode file objects. For these, use file.write(...) instead.

由于没有显式地传递 file 参数,所以 Python 会默认使用 sys.stdout

sys.stdout

查阅官方文档,节选片段:

When interactive, the stdout stream is line-buffered. Otherwise, it is block-buffered like regular text files. The stderr stream is line-buffered in both cases. You can make both streams unbuffered by passing the -u command-line option or setting the PYTHONUNBUFFERED environment variable.

stdout是有缓存的,只有遇到换行或者积累到一定的大小,才会显示出来。

解决方案

解决方案在 envvar-PYTHONUNBUFFERED 中其实已经说明了,有两种:

  • 设置环境变量 PYTHONUNBUFFERED
  • 运行 python 程序时,使用 -u 命令选项

在 Dockerfile 中我们只需这样一行设置即可:

ENV PYTHONUNBUFFERED=1

参考


image