Kubernetes · Updated 2026-11-19
How to compress Kubernetes logs before sending them to an LLM
When a pod keeps restarting, the log you hand to an LLM or an ops agent is mostly health checks, request lines and heartbeats, and the line that explains the crash can be anywhere in it. Pull a narrow slice with kubectl first, then compress what is left against the question you are asking, so the model reads the failure instead of the whole stream.
Why are Kubernetes logs so hard for an LLM to read?
A service log is mostly routine lines: health checks, request logs and heartbeats. The error that explains a restart can sit among them. After a crash the current container may have just started, so the useful lines are in the previous instance. Multi-container pods and several replicas multiply the volume. An LLM agent that ran kubectl logs <pod> -n <ns> --previous got a context_length_exceeded error back from the model API (kubectl-ai issue #290). Sending all of it costs input tokens and can bury the error under noise the model does not need.
Which kubectl flags cut the log down first?
Do the free trims first. Use --previous for the instance that crashed. Prefer -c <container> instead of --all-containers. Narrow the window with --since=30m or --since-time around the incident. Add --timestamps so the model can order events. Add --prefix and --tail=-1 when you pull several pods with -l, because with a selector kubectl logs otherwise returns only the last 10 lines per pod. Cap size with --limit-bytes when you need a hard ceiling. Before reading logs, check kubectl describe pod <pod> for the container's last state and termination reason; some crashes leave no error line in the log. A plain --tail is fragile because the first error can be earlier than the last lines. A grep for "error" is fragile too: it drops the lines around the match and misses failures that do not contain that word.
How do I compress pod logs with the SuperCompress API?
curl -X POST https://www.supercompress.dev/api/v1/compress \
-H "X-API-Key: $SUPERCOMPRESS_API_KEY" \
-H "Content-Type: application/json" \
-d '{"context": "<kubectl logs output>", "query": "Why did this pod restart, and what is the first error before it?"}'
import os
import sys
import subprocess
import requests
API_URL = "https://www.supercompress.dev/api/v1/compress"
POD = "POD" # replace with the pod name
NAMESPACE = "NAMESPACE" # replace with the namespace
QUESTION = "Why did this pod restart, and what is the first error before it?"
MAX_CHARS = 120000
cmd = [
"kubectl", "logs", POD,
"--previous", "--timestamps", "--since=1h",
"-n", NAMESPACE,
]
result = subprocess.run(cmd, capture_output=True, text=True)
if result.returncode == 0:
log_text = result.stdout
elif "previous terminated container" in result.stderr:
print(
"no previous instance exists; using the current container's logs",
file=sys.stderr,
)
cmd_without_previous = [
"kubectl", "logs", POD,
"--timestamps", "--since=1h",
"-n", NAMESPACE,
]
log_text = subprocess.check_output(cmd_without_previous, text=True)
else:
raise subprocess.CalledProcessError(
result.returncode, cmd, output=result.stdout, stderr=result.stderr
)
def js_len(s):
return len(s.encode("utf-16-le")) // 2
def line_chunks(text, limit):
lines = text.splitlines(keepends=True)
buf = []
size = 0
for line in lines:
line_len = js_len(line)
if size + line_len > limit and buf:
yield "".join(buf)
buf = []
size = 0
if line_len > limit:
piece = []
piece_size = 0
for ch in line:
ch_len = js_len(ch)
if piece_size + ch_len > limit and piece:
yield "".join(piece)
piece = []
piece_size = 0
piece.append(ch)
piece_size += ch_len
if piece:
yield "".join(piece)
continue
buf.append(line)
size += line_len
if buf:
yield "".join(buf)
parts = []
for chunk in line_chunks(log_text, MAX_CHARS):
kept = chunk # fail open: default to the original chunk
try:
r = requests.post(
API_URL,
headers={"X-API-Key": os.environ["SUPERCOMPRESS_API_KEY"]},
json={"context": chunk, "query": QUESTION},
timeout=60,
)
r.raise_for_status()
kept = r.json().get("compressed_text") or chunk
except requests.RequestException:
pass
parts.append(kept)
compressed_log = "".join(
p if p.endswith("\n") else p + "\n" for p in parts
)
The limit is counted the way JavaScript counts string length, so the example measures chunks in UTF-16 units. The context field is limited to 120,000 characters per call. Longer input returns HTTP 422 with "context too long (120k max)". Empty context returns 422 with "context required". SuperCompress is extractive and query-aware: it selects lines from the original rather than writing a summary, so error messages, pod and container names, timestamps and stack frames in the kept lines stay as written; preprocessing may rewrite JSON or collapse repeated stack frames before lines are chosen. Each response reports original_tokens and kept_tokens, which are estimates, not provider-billed totals. When the saving would be too small the call passes through: passthrough is true, compressed_text is the original and kept_tokens equals original_tokens. Coding agents running kubectl through a shell do not need to call this by hand: supercompress setup installs the MCP tool, plus hooks on agents that support them.
What question should I send?
Send the question you actually want answered. A good default is why the pod restarted and what the first error before it was. Use a narrower question if you already know a request id, an endpoint or a time. A generic request such as "summarize the logs" gets the broader digest labelled query_mode "dump". If you want two different answers from one log, compress once per question.
Does this work for docker logs and journalctl?
Yes. The API only sees text. Pull a window with docker logs --since 30m --timestamps <container> or journalctl -u <unit> --since "1 hour ago" --no-pager, then compress the output the same way. For failed builds rather than running services, see how to compress CI logs before an LLM reads them.
When are grep or describe enough?
Skip compression for short logs, when kubectl describe pod already shows the reason (for example a termination reason or an image pull failure in events), when you know the exact string to search for, and when you need the full log for an audit or a human. For a fuller decision guide, see when prompt compression is worth it.
How do I know it helped?
Run the same incidents with and without compression and check whether the model names the right first error. Log original_tokens and kept_tokens (estimates). Confirm cost on your provider bill. See whether context compression lowers your bill.
Frequently asked questions
Can I send a whole pod log in one call?
Only up to 120,000 characters of context per call. Narrow the slice with kubectl flags first, then split anything longer into chunks and compress each one.
Will compression change the error messages or timestamps?
SuperCompress selects original lines rather than writing a summary, so error messages, timestamps and pod names in the kept lines stay as written. Preprocessing may collapse repeated stack frames before lines are chosen.
Why not just use kubectl logs --tail?
The first error before a restart is often earlier than the last lines, and after a crash the current container may hold only startup lines. Pull the previous instance for the incident window and compress against your question instead of depending on where the error lands.
Do I need to send a question?
Yes, for a targeted result. Without a specific question, or with a generic one like "summarize the logs", the API returns a broader digest and labels the response query_mode "dump".