Monday, 3 March 2025

Using "grep" with "kubectl logs" to Filter Container/Pod Logs

 kubectl logs command helps us to inspect logs of pods in AKS/kubernetes and useful to diagnose issues. However, when there is too much logs it is harder to read through and find out errors easily. Further, filtering out logs for a given timestamp may be useful at times to identify the issues. In this post let's explore usage of grep with kubectl logs command to filter logs. 

Let's take first example to filter for a timestamp in keda operator pod logs. Here -i says to ignore case in logs.

kubectl logs keda-operator-79d756dd66-69gsc -n keda | grep -i '2025-03-04T07:20:24'


If it is necessary to filter for more than one criteria with OR, it is possible to use -e to specify each search criteria as shown below.

kubectl logs keda-operator-79d756dd66-69gsc -n keda | grep -i -e '2025-03-04T07:20:24' -e '2025-03-04T07:22:54'


Alternatively, it is possible use -E for expanding the filter criteria with OR operator as shown below as well.

kubectl logs keda-operator-79d756dd66-69gsc -n keda | grep -i -E '2025-03-04T07:20:24|2025-03-04T07:22:54'


When log by default does not have the timestamps, it is possible to use --timestamps with kubectl log and then grep it as shown below.

kubectl logs some-cronjob-29017980-xb5rl -n demo --timestamps | grep -i '2025-03-04T09:09:48'


To achive AND condition in filtering the log, it is possible to use grep result piping to another grep as shown below.

 kubectl logs some-cronjob-29017980-xb5rl -n demo --timestamps | grep -i 'cannot delete folder' | grep -i '2025-03-04T09:09'


Alternatively, it is possible to use -E with .* to specify any character pattern and then use a OR condition, to achive AND as shown below. It gives same results as above douple usage of grep.

 kubectl logs fileshare-cronjob-29017980-xb5rl -n avalanche --timestamps | grep -i -E 'cannot delete folder.*2025-03-04T09:09|2025-03-04T09:09.*cannot delete folder'



No comments:

Popular Posts