| name | retrieving-k8s-logs |
| description | Retrieves Kubernetes container logs with various patterns including multi-container pods, previous container logs, init containers, and label-based aggregation. Use when checking application logs, debugging crashes, or analyzing container output. |
| allowed-tools | Bash |
Retrieving Kubernetes Logs
Patterns for retrieving container logs effectively.
Basic Log Commands
kubectl logs <pod> -n <ns>
kubectl logs <pod> -n <ns> --tail=100
kubectl logs <pod> -n <ns> --since=1h
kubectl logs <pod> -n <ns> --since=30m
kubectl logs <pod> -n <ns> --timestamps
Multi-Container Pods
kubectl get pod <pod> -n <ns> -o jsonpath='{.spec.containers[*].name}'
kubectl logs <pod> -n <ns> -c <container>
kubectl logs <pod> -n <ns> --all-containers
Previous Container (After Crash)
kubectl logs <pod> -n <ns> --previous
kubectl logs <pod> -n <ns> -c <container> --previous
Use --previous when:
- Pod is in CrashLoopBackOff
- Container restarted and you need pre-crash logs
- Current container logs don't show the error
Init Container Logs
kubectl get pod <pod> -n <ns> -o jsonpath='{.spec.initContainers[*].name}'
kubectl logs <pod> -n <ns> -c <init-container-name>
Label-Based Log Aggregation
kubectl logs -l app=<app-name> -n <ns>
kubectl logs -l app=<app-name> -n <ns> --tail=50
kubectl logs -l app=<app-name> -n <ns> --all-containers
Searching Logs
kubectl logs <pod> -n <ns> | grep -i error
kubectl logs <pod> -n <ns> | grep -i -A5 -B5 "exception"
kubectl logs <pod> -n <ns> | grep -c "error"
Log Patterns for Debugging
Application Crash
kubectl logs <pod> -n <ns> --previous --tail=200
kubectl logs <pod> -n <ns> --previous | grep -i -E "error|exception|fatal|panic"
Startup Issues
kubectl logs <pod> -n <ns> | head -100
kubectl logs <pod> -n <ns> -c <init-container>
Intermittent Issues
kubectl logs <pod> -n <ns> --since=2h --timestamps
kubectl logs <pod> -n <ns> -f --tail=50
Memory Issues (OOM)
kubectl logs <pod> -n <ns> --previous | grep -i -E "memory|heap|oom|gc"
Log Output Formats
kubectl logs <pod> -n <ns>
kubectl logs -l app=<app> -n <ns> --prefix
kubectl logs <pod> -n <ns> --limit-bytes=50000
Quick Debugging Pattern
kubectl logs <pod> -n <ns> --tail=100 | grep -i error
kubectl logs <pod> -n <ns> --previous --tail=200
kubectl get pod <pod> -n <ns> -o jsonpath='{.spec.initContainers[*].name}'
kubectl logs <pod> -n <ns> -c <init-container>
kubectl logs <pod> -n <ns> --all-containers --tail=50
Notes
--previous only works if container restarted (keeps one previous log)
- Logs are ephemeral; they're lost when pod is deleted
- For persistent logs, use a logging stack (EFK, Loki, etc.)
- Load
debugging-k8s-pods for container state analysis