首页 > 解决方案 > 如何从 Python 进程登录到 Kubernetes 容器日志

问题描述

使用 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 occurred!'给容器,以便可以通过以下方式看到此错误消息:

kubectl describe pod pod_id

这有没有可能?

标签: pythonamazon-web-servicesdockerkubernetesamazon-eks

解决方案


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

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

try:
  ...
except:
  pass

默默地忽略try块外的任何和所有异常。bareexcept:甚至捕获了一些系统级异常,例如SystemExitor KeyboardInterrupt; 这几乎总是错误的。通常你希望你的except代码块的范围尽可能的小,关于用户定义异常的 Python 教程是一个很有帮助的模式。

(对此的例外情况,尤其是在 Kubernetes 上下文中,您通常需要一个非常广泛的异常处理程序来执行诸如向网络请求返回 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)

推荐阅读