登录
首页 >  Golang >  Go问答

如何在Kubernetes中运行的容器中获取日志?

来源:stackoverflow

时间:2024-03-12 19:12:27 103浏览 收藏

有志者,事竟成!如果你在学习Golang,那么本文《如何在Kubernetes中运行的容器中获取日志?》,就很适合你!文章讲解的知识点主要包括,若是你对本文感兴趣,或者是想搞懂其中某个知识点,就请你继续往下看吧~

问题内容

我有一个设计为作为 k8s 应用程序运行的应用程序,它导入了一些运行 exec.cmds 的依赖项(我不拥有)。这很好,但我想捕获这些日志。出于某种原因,当我这样做时:

r := bufio.NewReader(os.Stdout)

...

line, err := r.ReadString('\n')

抛出错误,指出 /dev/stdoutbad 文件描述符 。怎么会这样?这不是控制台输出的标准本地目的地吗?

kubectl logs 似乎能够捕获输出,更具体地说,我们的中央日志转发器也能够捕获它。但是尝试从实际生成这些日志的容器内的 kube api 服务器捕获日志似乎有点愚蠢......有更好的方法来做到这一点吗?


正确答案


通常,stdin 是一个只读流,用于检索写入程序的输入,而 stdout 是一个只写流,用于发送程序写入的输出。 换句话说,除了 chuck norris 之外,没有人可以读取 /dev/stdout。

默认情况下,stdout“指向”您的终​​端。但可以将 stdout 从终端重定向到文件。此重定向是在您的程序启动之前设置的。

通常发生的情况如下:容器运行时将容器进程的 stdout 重定向到容器运行的节点上的文件(例如,/var/log/containers/-.log)。当您使用 kubectl messages 请求日志时,kubectl 连接到 kube-apiserver,该服务器连接到运行容器的节点上的 kubelet,并要求它从日志文件发回内容。

另请参阅 https://kubernetes.io/docs/concepts/cluster-administration/logging/,其中解释了各种日志记录设计方法。

从安全性和可移植性的角度来看,您绝对不会实现的解决方案是在容器中添加 hostpath 挂载,挂载节点的 /var/log/containers 目录并直接访问容器日志。

正确的解决方案可能是更改映像的命令并将输出写入容器的 stdout 以及容器内的本地文件。这可以使用 tee 命令来实现。然后,您的应用程序可以从此文件读回日志。但请记住,如果没有适当的轮换,日志文件将会不断增长,直到您的容器被终止。

apiversion: v1
kind: pod
metadata:
  name: log-to-stdout-and-file
spec:
  containers:
  - image: bash:latest
    name: log-to-stdout-and-file
    command: 
    - bash
    - -c
    - '(while true; do date; sleep 10; done) | tee /tmp/test.log'

更复杂一点的解决方案是,将容器中的日志文件替换为使用 mkfifo 创建的命名管道文件。这避免了文件大小不断增长的问题(只要您的应用程序不断从命名管道文件读取日志)。

apiVersion: v1
kind: Pod
metadata:
  name: log-to-stdout-and-file
spec:
  # the init container creates the fifo in an empty dir mount
  initContainers:
  - image: bash:latest
    name: create-fifo
    command: 
    - bash
    - -c
    - mkfifo /var/log/myapp/log
    volumeMounts:
    - name: ed
      mountPath: /var/log/myapp

  # the actual app uses tee to write the log to stdout and to the fifo
  containers:
  - image: bash:latest
    name: log-to-stdout-and-fifo
    command: 
    - bash
    - -c
    - '(while true; do date; sleep 10; done) | tee /var/log/myapp/log'
    volumeMounts:
    - name: ed
      mountPath: /var/log/myapp

  # this sidecar container is only for testing purposes, it reads the
  # content written to the fifo (this is usually done by the app itself)
  #- image: bash:latest
  #  name: log-reader
  #  command: 
  #  - bash
  #  - -c
  #  - cat /var/log/myapp/log
  #  volumeMounts:
  #  - name: ed
  #    mountPath: /var/log/myapp

  volumes:
  - name: ed
    emptyDir: {}

您应该考虑将带有主/应用容器和日志容器的多容器 pod 作为从主/应用容器读取日志的边车容器。考虑下面链接中的示例,显示如何从主容器尾部日志

https://learnk8s.io/sidecar-containers-patterns

终于介绍完啦!小伙伴们,这篇关于《如何在Kubernetes中运行的容器中获取日志?》的介绍应该让你收获多多了吧!欢迎大家收藏或分享给更多需要学习的朋友吧~golang学习网公众号也会发布Golang相关知识,快来关注吧!

声明:本文转载于:stackoverflow 如有侵犯,请联系study_golang@163.com删除
相关阅读
更多>
最新阅读
更多>
课程推荐
更多>