Linux Commands / IT Support Guides
Search Linux logs with grep and context
Use grep to find an error message in a log and show the lines around it.
Environment and inputs: Linux · Bash-compatible shell; package and service names vary by distribution
Understand the problem
Start with the log for the application that reported the error. Use a copy if you are investigating away from the original machine.
Run the command
Replace /var/log/app/app.log with the log you want to read. The -n option adds line numbers, -i ignores uppercase and lowercase differences, and -C 3 shows up to three lines on either side of each match.
grep -n -i -C 3 -- 'connection refused' /var/log/app/app.log
Read the output
A result such as 2:Connection refused means the message matched on line 2. Nearby lines are context. Look for the timestamp, environment, and destination before forming a conclusion.
Choose the next step
If grep prints nothing, check its exit status immediately with echo $?. Status 1 means no line matched, while status 2 means an error occurred. Check the path and time range or try a shorter phrase.
Before making changes
A match shows where the message appeared. Compare the surrounding events before deciding what caused it, and remove sensitive values before sharing excerpts.