python - 如何从 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
这有没有可能?
解决方案
您print()
将在 中可见的任何内容kubectl logs
。(您可能需要PYTHONUNBUFFERED=1
在 pod 规范中设置环境变量。)
您编写的代码永远不会打印任何内容。构造
try:
...
except:
pass
默默地忽略try
块外的任何和所有异常。bareexcept:
甚至捕获了一些系统级异常,例如SystemExit
or 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)
推荐阅读
- html - 背景过滤器不适用于标签
我想为表格标签中的每一行赋予 Glassmorphism 效果,并且背景过滤器不适用于 tr 标签。如何为行或任何替代 CSS 属性赋予模糊效果以实现它?
amazon-dynamodb - 在 DynamoDB 上,客户端是否可以指定时间戳来确定最近的更新,以便最近的数据始终保留在表中
- postgresql - Apple MacBook Pro M1 芯片 + Postgres + Connection denied 错误
- laravel - 为什么 Laravel Storage Exists 函数返回 true 但 readStream 返回 null
- r - 用于过滤掉 R 数据框列的重复数字的正则表达式
- bigcommerce - 我如何在购物车页面上添加一个按钮,允许客户“清空购物车”。在大商业中
- android - 单次垂直单击更改 RecyclerView 中的焦点
- node.js - 如何在 nodejs 服务器中处理批量 api 请求?
- c++ - 如何为函数的参数使用无限数量的结构?
- c# - 在 Xamarin Forms 中使用 SkiaSharp 绘制现有图像