print logs from Kubernetes api

11/4/2016

I was wondering if there is a possibility to continuously print logs from HTTP request to Kubernetes API. I am using python for querying K8S API sth like

r = requests.get(self.url + "namespaces/" + namespace + "/pods/" + pod_name + "/log", cert=(self.cert, self.key), verify=False)

and i would like to use follow=true parameter probably together with tailLines=100 to make it more like tail command.

When I am using follow parameter the request is collecting response but i don't know how to forward it's output to console. Is it possible?

-- widget
api
kubernetes
python
python-requests

2 Answers

11/4/2016

What i was missing is stream=True in request.get parameter which allows to iterate through the response content so my code looks like this:

import requests

class Logs():
    def __init__(self, url='https://192.168.0.1:6443/api/v1/',
                 cert='./client.crt',
                 key='./client.key'):
        self.url = url
        self.cert = cert
        self.key = key
        requests.packages.urllib3.disable_warnings()

    def get_pod_logs(self, namespace, pod_name):

        params = dict(
            follow="true",
            tailLines="100"
        )

        r = requests.get(self.url + "namespaces/" + namespace + "/pods/" + pod_name + "/log", params=params,
                         cert=(self.cert, self.key), verify=False, stream=True)

        for chunk in r.iter_content(chunk_size=256):
            if chunk:
                print(chunk)

logs = Logs()

logs.get_pod_logs(namespace="my-ns",pod_name="my-pod")
-- widget
Source: StackOverflow

11/4/2016

You're almost there. I think what you want is the following:

kubectl logs -f <your-pod-name> --tail=100

You can get pod names with the following command:

kubectl get pods

Hope that helps

-- Michel Tresseras
Source: StackOverflow