Single command to display logs from running kubernetes pod

11/8/2018

Want to have a single command to have continue streaming of logs from particular pod. Currently I have to do

  • kubectl get pods (lists all the running pods)
  • check for the running pod from the list and copy the pod name
  • kubectl logs <pod name> -f (continuous streaming of logs from pod)

Bonus points: list pods starting with certain word like, kubectl get pods asset*. Which would just display pods with names starting with asset

-- Anuj
kubectl
kubernetes

4 Answers

11/9/2018

You can use awk to achieve this. You can use:

kubectl logs -n <namespace> $(kubectl get pod -n <namespace> |  awk '/<pattern>/{print $1}') -f

Here, you can specify regex in <pattern> field. print $1 prints only first column of matched object. In our case, it is pod name.

For example:

kubectl logs -n kube-system $(kubectl get pod -n kube-system |  awk '/kube-proxy*/{print $1}') -f
-- Emruz Hossain
Source: StackOverflow

11/8/2018

You can use some bash tricks to get that :

Example:

Get the logs for pod starting with name pattern core in kube-system namespace.

kubectl logs --namespace=kube-system $(kubectl get pods --namespace=kube-system -o go-template --template '{{range .items}}{{.metadata.name}}{{"\n"}}{{end}}' | grep core)

or even simple:

kubectl logs --namespace=kube-system $(kubectl get pods -o=name --all-namespaces | grep core)

but in production you should use fluentbit to stream the logs to ELK and then use filters in kibana UI to get the logs for each pod/deployment/namespace etc.

https://github.com/fluent/fluent-bit-kubernetes-logging

-- Ijaz Ahmad Khan
Source: StackOverflow

11/8/2018

you can get all result by kubectl get pods and grep can do the rest of things.

[root@k8s-m1 ~]# kubectl get pods | grep httpd*-app
httpd-app-66cb7d499b-4nfl4   1/1     Running   0          6m39s
httpd-app-66cb7d499b-c2blq   1/1     Running   0          6m39s
httpd-app-66cb7d499b-dt4tr   1/1     Running   0          6m39s
-- Vi.Ci
Source: StackOverflow

11/9/2018

Finally was able to figure out the solution. This would be somewhat hacky, but I would basically use --field-selector=status.phase=Running and just get the name with -o=name flag. My final command would be something like

kubectl logs -f $(kubectl get pods --field-selector=status.phase=Running -o=name | awk '/asset/ {print $1;exit}')

Links: Field Selectors

-- Anuj
Source: StackOverflow