Master Log Searching with grep, tail, and less: Real‑World Tips for Developers
This guide walks you through practical command‑line techniques—using grep, tail, less, and related options—to efficiently locate Java exceptions in log files, view surrounding context, monitor live logs, search compressed archives, and quickly count occurrences, all without opening files manually.
Preface
A new colleague struggled with log inspection, using naive commands like tail -f a.log | grep "java.lang.NullPointerException" that only displayed a single matching line, making it hard to see stack traces.
Formal Teaching
The core tool is the grep command. Below are several practical scenarios.
Scenario 1: View full exception stack
Java stack traces span multiple lines, so grep "NullPointerException" shows only the first line. Use the -A (after) option to display the matching line plus N following lines:
# Show the matching line and the next 50 lines
grep -A 50 "java.lang.NullPointerException" a.logIf the output scrolls too fast, pipe it to less for paging:
grep -A 50 "java.lang.NullPointerException" a.log | lessIn the less view you can:
Use ↑/↓ or Page Up/Down to scroll.
Press G to jump to the end of the file.
Enter /Exception to search forward.
Press q to quit.
Signed-in readers can open the original source through BestHub's protected redirect.
This article has been distilled and summarized from source material, then republished for learning and reference. If you believe it infringes your rights, please contactand we will review it promptly.
Code Ape Tech Column
Former Ant Group P8 engineer, pure technologist, sharing full‑stack Java, job interview and career advice through a column. Site: java-family.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.
