How to get log and describe of pods in kubernetes by python client

You can read the logs of a pod using the following code:

from kubernetes.client.rest import ApiException
from kubernetes import client, config

config.load_kube_config()
pod_name = "counter"
try:
    api_instance = client.CoreV1Api()
    api_response = api_instance.read_namespaced_pod_log(name=pod_name, namespace='default')
    print(api_response)
except ApiException as e:
    print('Found exception in reading the logs')

The above code works perfectly fine for getting the logs of pod.

To get the output of kubectl describe pod, all the information provided is in read_namespaced_pod function. It has all the information you require, and you can use that information in whatever way you require. You can edit the above code and use read_namespaced_pod in place of read_namespaced_pod_log to get the info.


As Kubernetes is using REST API, which gives you every possibility that you can call logs and description of objects via python.

Firstly you need to find out your authorization mechanism. You can find it via according your cluster.

kubectl config view --raw

Then you can create api call with this auth method. In below example, I used basic auth for getting pod logs for example.

import json
import requests
from requests.auth import HTTPBasicAuth
user='admin'
password='password'
url='https://cluster-api-url/api/v1/namespaces/default/pods/nginx-ingress-controller-7bbcbdcf7f-dgr57/log'

requests.packages.urllib3.disable_warnings()
resp = requests.get(url, auth=HTTPBasicAuth(user, password), verify=False, json=False)
print(resp.text)

To get the url easily, type command with "--v=8" argument. For example to get url for describe the pod

kubectl describe pod nginx-ingress-controller-7bbcbdcf7f-dgr57 --v=8

and check above part of your real output

I0514 12:31:42.376972  216066 round_trippers.go:383] GET https://cluster-api-url/api/v1/namespaces/default/events?fieldSelector=involvedObject.namespace%3Ddefault%2CinvolvedObject.uid%3D1ad92455-7589-11e9-8dc1-02a3436401b6%2CinvolvedObject.name%3Dnginx-ingress-controller-7bbcbdcf7f-dgr57
I0514 12:31:42.377026  216066 round_trippers.go:390] Request Headers:
I0514 12:31:42.377057  216066 round_trippers.go:393]     Accept: application/json, */*
I0514 12:31:42.377074  216066 round_trippers.go:393]     Authorization: Basic YWRtaW46elRoYUJoZDBUYm1FbGpzbjRtYXZ2N1hqRWlvRkJlQmo=
I0514 12:31:42.377090  216066 round_trippers.go:393]     User-Agent: kubectl/v1.12.0 (linux/amd64) kubernetes/0ed3388

Copy URL from GET https://<URL> part and change with url in your python script, then you go.

Hope it helps