dongpao5261 2018-12-19 13:42
浏览 664
已采纳

如何使用Golang从Kubernetes获取日志?

I'm looking for the solution of how to get logs from a pod in Kubernetes cluster using golang. I've looked at "https://github.com/kubernetes/client-go" and "https://godoc.org/sigs.k8s.io/controller-runtime/pkg/client", but couldn't understand how to use them for this purpose. I have no issues getting information of a pod or any other object in K8S except for logs.

For example, I'm using Get() from "https://godoc.org/sigs.k8s.io/controller-runtime/pkg/client#example-Client--Get" to get K8S job info:

found := &batchv1.Job{}
err = r.client.Get(context.TODO(), types.NamespacedName{Name: job.Name, Namespace: job.Namespace}, found)

Please share of how you get pod's logs nowadays. Any suggestions would be appreciated!

Update: The solution provided in Kubernetes go client api for log of a particular pod is out of date. It have some tips, but it is not up to date with current libraries.

  • 写回答

3条回答 默认 最新

  • dongtan9066 2018-12-20 14:08
    关注

    Here is what we came up with eventually using client-go library:

    func getPodLogs(pod corev1.Pod) string {
        podLogOpts := corev1.PodLogOptions{}
        config, err := rest.InClusterConfig()
        if err != nil {
            return "error in getting config"
        }
        // creates the clientset
        clientset, err := kubernetes.NewForConfig(config)
        if err != nil {
            return "error in getting access to K8S"
        }
        req := clientset.CoreV1().Pods(pod.Namespace).GetLogs(pod.Name, &podLogOpts)
        podLogs, err := req.Stream()
        if err != nil {
            return "error in opening stream"
        }
        defer podLogs.Close()
    
        buf := new(bytes.Buffer)
        _, err = io.Copy(buf, podLogs)
        if err != nil {
            return "error in copy information from podLogs to buf"
        }
        str := buf.String()
    
        return str
    }
    

    I hope it will help someone. Please share your thoughts or solutions of how you get logs from pods in Kubernetes.

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(2条)

报告相同问题?

悬赏问题

  • ¥15 请教:如何用postman调用本地虚拟机区块链接上的合约?
  • ¥15 为什么使用javacv转封装rtsp为rtmp时出现如下问题:[h264 @ 000000004faf7500]no frame?
  • ¥15 乘性高斯噪声在深度学习网络中的应用
  • ¥15 运筹学排序问题中的在线排序
  • ¥15 关于docker部署flink集成hadoop的yarn,请教个问题 flink启动yarn-session.sh连不上hadoop,这个整了好几天一直不行,求帮忙看一下怎么解决
  • ¥15 深度学习根据CNN网络模型,搭建BP模型并训练MNIST数据集
  • ¥15 C++ 头文件/宏冲突问题解决
  • ¥15 用comsol模拟大气湍流通过底部加热(温度不同)的腔体
  • ¥50 安卓adb backup备份子用户应用数据失败
  • ¥20 有人能用聚类分析帮我分析一下文本内容嘛