Back to lessons

Apple Terminal

Search a Log for Errors With Context

A local log contains too many lines to manually scan for the relevant failure.

Command

grep -n -C 2 'ERROR' ./app.log

What changed

Nothing changes. The command prints matching lines with line numbers and nearby context.

Danger

safe

When to use it

Use when debugging build logs, app logs, export logs, or CLI output saved to a file.

When not to use it

Do not use it for structured JSON analysis when jq would be more precise.

Undo or recovery

No undo needed because this command is read-only.

Expected output

Matching ERROR lines with two lines before and after each match.

demo script

Disposable terminal steps

  1. nl -ba project/logs/app.log | sed -n '1,8p'
  2. grep -n -C 2 'ERROR' project/logs/app.log

simulated output

What it looks like

disposable vessel
::fixture-ready::
$ nl -ba project/logs/app.log | sed -n '1,8p'
     1	server started
     2	loading config
     3	ERROR missing API_KEY
     4	retry disabled
     5	exit
::exit-code::0
$ grep -n -C 2 'ERROR' project/logs/app.log
1-server started
2-loading config
3:ERROR missing API_KEY
4-retry disabled
5-exit
::exit-code::0

YouTube Short

Find errors faster.

grep can show line numbers and context. Dash C two gives you the match plus two lines before and after.

LinkedIn hook

A wall of logs is useless until you pull the error and the lines around it.

Question: Do you usually search logs directly, or save command output to a file first?

experiments

A/B tests to run

Metric: save_rate

A: Use -C 2 for compact context.

B: Use -C 5 for fuller context.