How to get logs from kubernetes using golang?

前端 未结 4 1779
情话喂你
情话喂你 2020-12-17 00:59

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://god

4条回答
  •  一整个雨季
    2020-12-17 01:31

    And if you want read stream in client-go v11.0.0+, the code is like this, feel free for create clientset by yourself:

    func GetPodLogs(namespace string, podName string, containerName string, follow bool) error {
        count := int64(100)
        podLogOptions := v1.PodLogOptions{
            Container: containerName,
            Follow:    follow,
            TailLines: &count,
        }
    
        podLogRequest := clientSet.CoreV1().
            Pods(namespace).
            GetLogs(podName, &podLogOptions)
        stream, err := podLogRequest.Stream(context.TODO())
        if err != nil {
            return err
        }
        defer stream.Close()
    
        for {
            buf := make([]byte, 2000)
            numBytes, err := stream.Read(buf)
            if numBytes == 0 {
                continue
            }
            if err == io.EOF {
                break
            }
            if err != nil {
                return err
            }
            message := string(buf[:numBytes])
            fmt.Print(message)
        }
        return nil
    }
    
    

提交回复
热议问题