What kubectl command can I use to get events sorted by specific fields and print only specific details of events?
Asked Answered
S

5

87

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?

Sally answered 20/7, 2017 at 23:31 Comment(1)
#45310787 (my answer: kubectl alpha events https://mcmap.net/q/150296/-kubernetes-sort-pods-by-age-closed)Drisko
L
147

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

Lustrous answered 25/4, 2019 at 22:18 Comment(1)
in case this throws an error, try this kubectl get events --sort-by=.metadata.creationTimestamp.Lamprophyre
S
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}}'
Sally answered 20/7, 2017 at 23:31 Comment(0)
A
14

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

Alcorn answered 16/12, 2020 at 9:35 Comment(0)
F
8

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

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

This requires jq.

Furriery answered 11/6, 2018 at 16:7 Comment(0)
R
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.

Refusal answered 19/6, 2020 at 17:17 Comment(2)
But what is "oc" referring to?Vapory
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.Refusal

© 2022 - 2024 — McMap. All rights reserved.