Linux Survival Basics
Show Context Around the First App Error
An application log has many lines, and you need the few lines leading into the first error.
Command
awk '{buf[NR%5]=$0} tolower($0) ~ /(error|exception|fatal)/ {for (i=NR-4;i<=NR;i++) if (i>0) print buf[i%5]; exit}' fixtures/incidents/app.log
What changed
Nothing changes. The command prints buffered context around the first severe application line.
Danger
safe
When to use it
Use when the first failure context matters more than repeated downstream errors.
When not to use it
Do not use it when you need every occurrence; this intentionally exits after the first match.
Undo or recovery
No undo needed because the command is read-only.
Expected output
Several lines ending at the first error, exception, or fatal log entry.
demo script
Disposable terminal steps
head -8 fixtures/incidents/app.logawk '{buf[NR%5]=$0} tolower($0) ~ /(error|exception|fatal)/ {for (i=NR-4;i<=NR;i++) if (i>0) print buf[i%5]; exit}' fixtures/incidents/app.log
simulated output
What it looks like
::fixture-ready::
$ head -8 fixtures/incidents/app.log
2026-06-25T14:00:01Z level=INFO service=api request_id=req-100 msg=started release=2026.06.25.1
2026-06-25T14:01:14Z level=INFO service=worker request_id=req-101 msg=queue_depth value=18
2026-06-25T14:02:06Z level=WARN service=api request_id=req-102 msg=upstream_slow upstream=db latency_ms=2200
2026-06-25T14:03:08Z level=ERROR service=api request_id=req-103 msg=database_timeout timeout_ms=30000
2026-06-25T14:03:12Z level=ERROR service=api request_id=req-103 msg=retry_failed upstream=db
2026-06-25T14:04:44Z level=INFO service=deploy request_id=req-104 msg=release_switch release=2026.06.25.2
2026-06-25T14:05:10Z level=FATAL service=worker request_id=req-105 msg=job_runner_exit code=137
2026-06-25T14:05:12Z level=INFO service=system request_id=req-106 msg=worker_restarted
::exit-code::0
$ awk '{buf[NR%5]=$0} tolower($0) ~ /(error|exception|fatal)/ {for (i=NR-4;i<=NR;i++) if (i>0) print buf[i%5]; exit}' fixtures/incidents/app.log
2026-06-25T14:00:01Z level=INFO service=api request_id=req-100 msg=started release=2026.06.25.1
2026-06-25T14:01:14Z level=INFO service=worker request_id=req-101 msg=queue_depth value=18
2026-06-25T14:02:06Z level=WARN service=api request_id=req-102 msg=upstream_slow upstream=db latency_ms=2200
2026-06-25T14:03:08Z level=ERROR service=api request_id=req-103 msg=database_timeout timeout_ms=30000
::exit-code::0
YouTube Short
Find first-error context.
Repeated errors can bury the useful clue. Buffer a few lines and stop at the first severe app message.
LinkedIn hook
The first error often explains more than the last one.
Question: Do you inspect the first failure or the loudest repeated failure first?
experiments
A/B tests to run
Metric: save_rate
A: The first error is the clue.
B: Stop after the first severe line.