如何使用Golang从Kubernetes获取日志? [英] How to get logs from kubernetes using golang?

查看:805
本文介绍了如何使用Golang从Kubernetes获取日志?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在寻找如何使用golang从Kubernetes集群的pod中获取日志的解决方案.我看过" https://github.com/kubernetes/client-go "和" https://godoc.org/sigs.k8s.io/controller- runtime/pkg/client ",但无法理解如何为此目的使用它们.除了日志,我在获取K8S中的Pod或任何其他对象的信息方面都没有问题.

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.

例如,我正在使用" https://godoc.org/sigs.k8s.io/controller-runtime/pkg/client#example-Client--Get 以获得K8S职位信息:

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)

请分享当今如何获取Pod的日志. 任何建议,将不胜感激!

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

更新: > Kubernetes提供的解决方案是客户端api,用于记录日志特定的广告连播已过时.它有一些技巧,但不是最新的库.

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.

推荐答案

以下是我们最终使用客户端库的想法:

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
}

我希望它能对某人有所帮助.请分享您对如何从Kubernetes的吊舱中获取日志的想法或解决方案.

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

这篇关于如何使用Golang从Kubernetes获取日志?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆