Skip to main content

Context Lines

When investigating errors or tracing code flow, you rarely just want the matching line — you need the surrounding context.

The Three Context Flags

FlagMeaningUse Case
-A N / --after-context=NN lines after matchSee what happens after an error
-B N / --before-context=NN lines before matchSee state leading up to an error
-C N / --context=NN lines both sidesGeneral debugging

Examples

# View a Python exception plus the 10-line stack trace below it
rg -A 10 "Exception:" app.log

# See the 5 lines of config before a "failed" line
rg -B 5 "failed to connect" server.log

# Get full context around a database error
rg -C 3 "Deadlock found" mysql-slow.log

Reading Multi-line Stack Traces

Java stack traces begin with an exception line and have many following lines of class paths. Use -A to capture the full trace:

rg -A 30 "java\.lang\.NullPointerException" application.log

Then if you only want unique exception types:

rg -o "java\.lang\.\w+Exception" application.log | sort -u

Context Separator

When rg finds multiple matches with context, it inserts a -- separator between non-contiguous groups:

app.log
42- connecting to database
43: ERROR: connection refused ← match
44- retrying in 5 seconds
--
102- user login attempt
103: ERROR: invalid credentials ← match
104- locking account after 3 fails

Suppress the separator with --no-context-separator when piping to scripts:

rg -C 2 "ERROR" app.log --no-context-separator | process_errors.sh