如何从 Python 进程记录到 Kubernetes 容器日志

How to log to Kubernetes Container Log from Python process

使用 Kubernetes 容器 运行 一个 Python 脚本:

import time
while True:
    try:
        for i in range(10):
            if i==0:
                raise Exception('Exception occurred!')
    except:
        pass
    time.sleep(1)

我想将 Exception 的消息 'Exception occurred!' 传递给 Container,以便可以通过以下方式查看此错误消息:

kubectl describe pod pod_id

有可能吗?

print() 的任何内容都将在 kubectl logs 中可见。 (您可能需要在 Pod 规范中设置环境变量 PYTHONUNBUFFERED=1。)

您编写的代码永远不会打印任何内容。构造

try:
  ...
except:
  pass

默默地忽略 try 块之外的所有异常。裸 except: 甚至捕获一些系统级异常,如 SystemExitKeyboardInterrupt;这几乎总是错误的。通常您希望 except 块的范围尽可能小,user-defined exceptions 上的 Python 教程是一个有用的模式。

(例外情况,尤其是在 Kubernetes 上下文中,您通常需要一个非常广泛的异常处理程序来对网络请求执行 return HTTP 500 错误之类的操作,而不是崩溃申请。)

更好的示例可能如下所示:

import time

class OneException(Exception):
  pass

def iteration():
  for i in range(10):
    try:
      if i == 1:
        raise OneException("it is one")
      print(i, math.sqrt(i), math.sqrt(-i))
      # will work when i==0 but fail when i==2
    except OneException as e:
      print(i, repr(e))
      # and proceed to the next iteration

if __name__ == '__main__':
  while True:
    # The top-level loop.  We want a very broad catch here.
    try:
      iteration()
    except Exception as e:
      print('iteration failed', repr(e))
    time.sleep(1)