Master Log Debugging with grep, tail, and less: Real‑World Tips
This guide walks you through practical techniques for quickly locating Java NullPointerException traces in plain, rotating, and compressed log files using grep, tail, less, and related options, covering context display, real‑time monitoring, compressed‑log searching, and occurrence counting.
Introduction
A junior teammate struggled to find useful information in error logs, using only simple tail and grep commands that showed a single line without stack context. The author shares a set of practical commands to make log inspection fast and comprehensive.
Core Tool: grep
Scenario 1: View full stack trace
Java stack traces span multiple lines, so a plain grep "NullPointerException" only shows the first line. Use the -A (after) option to display following lines.
grep -A 50 "java.lang.NullPointerException" a.logPipe the result to less for paging and navigation.
grep -A 50 "java.lang.NullPointerException" a.log | lessUse ↑/↓ or Page Up/Down to scroll.
Press G to jump to the end of the file.
Search within less with /Exception.
Press q to quit.
Scenario 2: Real‑time monitoring
When an application is running, combine tail -f with grep -A to instantly see new matching lines and their surrounding context.
tail -f a.log | grep -A 50 "java.lang.NullPointerException"Stop monitoring with Ctrl + C.
Add -i to ignore case.
Scenario 3: Search compressed logs
Log files are often rotated and compressed (e.g., .log.2025-07-02.gz). Use grep -H -A 50 for plain logs and zgrep for compressed ones.
grep -H -A 50 "java.lang.NullPointerException" *.log zgrep -H -A 50 "java.lang.NullPointerException" *.gz zgrepworks like grep but reads .gz files without manual decompression.
Scenario 4: Count occurrences
To quickly assess how frequent an exception appears, use the -c (count) option.
grep -c "java.lang.NullPointerException" a.log grep -c "java.lang.NullPointerException" *.logOther useful grep options
-B N: show N lines before the match. -A N: show N lines after the match. -C N: show N lines of context (both before and after). -i: ignore case. -H: print the matching file name. -r: recursively search directories.
Su San Talks Tech
Su San, former staff at several leading tech companies, is a top creator on Juejin and a premium creator on CSDN, and runs the free coding practice site www.susan.net.cn.
How this landed with the community
Was this worth your time?
0 Comments
Thoughtful readers leave field notes, pushback, and hard-won operational detail here.
