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
| Flag | Meaning | Use Case |
|---|---|---|
-A N / --after-context=N | N lines after match | See what happens after an error |
-B N / --before-context=N | N lines before match | See state leading up to an error |
-C N / --context=N | N lines both sides | General 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