76

I need to print only specific fields of Kubernetes Events, sorted by a specific field.

This is to help me gather telemetry and analytics about my namespace

How could I do that?

suryakrupa
  • 3,852
  • 1
  • 25
  • 34
  • https://stackoverflow.com/questions/45310287/kubernetes-sort-pods-by-age/73614140 (my answer: `kubectl alpha events` https://stackoverflow.com/a/73614140/67824) – Ohad Schneider Sep 05 '22 at 19:58

5 Answers5

121

kubectl get events --sort-by='.lastTimestamp'

ehbello
  • 1,235
  • 1
  • 8
  • 3
41

Following command does it.

It prints the events sorted by timestamp of creation.

It also users go-template to filter out specific fields of the kubernetes-event object.

kubectl get events  --sort-by='.metadata.creationTimestamp'  -o 'go-template={{range .items}}{{.involvedObject.name}}{{"\t"}}{{.involvedObject.kind}}{{"\t"}}{{.message}}{{"\t"}}{{.reason}}{{"\t"}}{{.type}}{{"\t"}}{{.firstTimestamp}}{{"\n"}}{{end}}'
suryakrupa
  • 3,852
  • 1
  • 25
  • 34
12

I am using the following command to sort it after timestamp

kubectl get event --all-namespaces --sort-by='.metadata.managedFields[0].time'

For filtering out the information you can of course combine it with the go-template described by @suryakrupa or with jq described by @Chris Stryczynski

Timtation
  • 321
  • 3
  • 6
8

If you don't mind seeing the output as JSON:

kubectl get event -o json | jq '.items |= sort_by(.lastTimestamp)'

This requires jq.

Chris Stryczynski
  • 30,145
  • 48
  • 175
  • 286
1

Here's the Bash function I use:

function kubectl-events {
    {
        echo $'TIME\tNAMESPACE\tTYPE\tREASON\tOBJECT\tSOURCE\tMESSAGE';
        kubectl get events -o json "$@" \
            | jq -r  '.items | map(. + {t: (.eventTime//.lastTimestamp)}) | sort_by(.t)[] | [.t, .metadata.namespace, .type, .reason, .involvedObject.kind + "/" + .involvedObject.name, .source.component + "," + (.source.host//"-"), .message] | @tsv';
    } \
        | column -s $'\t' -t \
        | less -S
}

You can use it like: kubectl-events -A, kubectl-events -n foo, etc.

philraj
  • 820
  • 6
  • 13
Sam Morris
  • 1,858
  • 1
  • 17
  • 18
  • But what is "oc" referring to? – philraj Apr 14 '21 at 17:28
  • 1
    Haha good question. `oc` is the OpenShift client that is basically `kubectl` + extra support for OpenShfit features. I am so used to typing it that I forgot to edit my answer to make it use `kubectl` instead. – Sam Morris Apr 15 '21 at 07:38