121

kubectl logs -f pod shows all logs from the beginning and it becomes a problem when the log is huge and we have to wait for a few minutes to get the last log. Its become more worst when connecting remotely. Is there a way that we can tail the logs for the last 100 lines of logs and follow them?

5 Answers 5

215

In a cluster best practices are to gather all logs in a single point through an aggregator and analyze them with a dedicated tool. For that reason in K8S, log command is quite basic.

Anyway kubectl logs -h shows some options useful for you:

# Display only the most recent 20 lines of output in pod nginx
kubectl logs --tail=20 nginx

# Show all logs from pod nginx written in the last hour
kubectl logs --since=1h nginx

Some tools with your requirements (and more) are available on github, some of which are:

4
  • 8
    also --timestamps is helpful if you need logs with timestamps
    – surazzarus
    Jun 20, 2019 at 13:55
  • New to this stuff, are there any official recommendations for how to aggregate the logs? Mar 30, 2021 at 15:22
  • fluentd, logstash, look in google for other.
    – Nicola Ben
    Mar 31, 2021 at 10:39
  • 5
    Is there a way to view the start of the logs? Like --head=50 would show me the first 50 lines of the logs? I did run kubectl logs -h to see all options but couldn't find one that returns the head of logs.
    – Ram Patra
    Jul 29, 2021 at 11:21
45

Try kubectl logs -f pod --tail=10

12

To fetch tail lines from logs of a pod with multi containers.

kubectl logs <pod name> --all-containers=true --tail=10

To fetch tail lines from logs of pods within an application:

kubectl logs --selector app=<your application> --tail=10

(ex:if your application has 3 pods then output of above command can be 30 logs 10 of each pod logs)

9

You can ues this way to get the first 10 lines

kubectl logs my-pod-name  -n my-ns | head -n 10
1
  • 2
    They are looking for the last 100 lines, not the first lines
    – Ascalonian
    Feb 23, 2022 at 16:20
0

You can also follow logs from the end if you are testing something:

kubectl logs my-pod-name --follow

This will work just like running tail -f in bash or other shells.

1
  • This doesn't answer the OPs question and results in the same problem for large logs. You should consider removing this answer, else it will get down voted
    – fose
    May 17, 2021 at 7:00

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

Not the answer you're looking for? Browse other questions tagged or ask your own question.