0
0
KubernetesHow-ToBeginner · 3 min read

How to Collect Logs in Kubernetes: Simple Commands and Tips

To collect logs in Kubernetes, use the kubectl logs command followed by the pod name to see container logs. For multiple containers or pods, specify the container name or use label selectors. For centralized logging, deploy tools like Fluentd or Elasticsearch.
📐

Syntax

The basic syntax to collect logs from a pod in Kubernetes is:

  • kubectl logs [pod-name]: Shows logs from the default container in the pod.
  • kubectl logs [pod-name] -c [container-name]: Shows logs from a specific container if the pod has multiple containers.
  • kubectl logs -l [label-selector]: Shows logs from pods matching the label selector.
  • kubectl logs [pod-name] --since=1h: Shows logs from the last hour.
bash
kubectl logs my-pod
kubectl logs my-pod -c my-container
kubectl logs -l app=myapp
kubectl logs my-pod --since=1h
💻

Example

This example shows how to get logs from a pod named nginx-pod and from a specific container nginx-container inside that pod.

bash
kubectl logs nginx-pod
kubectl logs nginx-pod -c nginx-container
Output
2024/06/01 12:00:00 [notice] 1#1: start worker process 10 2024/06/01 12:00:01 [info] 10#1: GET /index.html 200
⚠️

Common Pitfalls

Common mistakes when collecting logs in Kubernetes include:

  • Not specifying the container name when the pod has multiple containers, which causes an error.
  • Trying to get logs from a pod that has already terminated without using --previous to see logs from the last container instance.
  • Not using label selectors correctly, leading to no logs or too many logs.
bash
kubectl logs my-pod
# Error if multiple containers exist

kubectl logs my-pod -c my-container
# Correct way to specify container

kubectl logs my-pod --previous
# Get logs from previous container instance
📊

Quick Reference

CommandDescription
kubectl logs [pod-name]Show logs from the default container in the pod
kubectl logs [pod-name] -c [container-name]Show logs from a specific container
kubectl logs -l [label-selector]Show logs from pods matching labels
kubectl logs [pod-name] --since=1hShow logs from the last hour
kubectl logs [pod-name] --previousShow logs from the previous container instance

Key Takeaways

Use kubectl logs [pod-name] to quickly see logs from a pod's container.
Specify -c [container-name] if the pod has multiple containers to avoid errors.
Use label selectors with kubectl logs -l [label] to collect logs from multiple pods.
Use --previous to view logs from a terminated container instance.
For large-scale logging, deploy centralized logging tools like Fluentd or Elasticsearch.