Find the log entries you need in project files
🎯 Introduction
Paging through hundreds of log lines is slow. Starting with the app.log from the previous article, you will find common Node.js service errors and save the results as a troubleshooting report.
🧱 Decide whether you need a file or its contents
find searches for files below a specified directory; grep finds matching lines in files or incoming text. First locate log files in the practice directory, then inspect their error lines.
cd "$HOME/linux-lab"
find . -type f -name '*.log'
grep -n 'ERROR' logs/app.log
-type f selects only regular files, and -name matches filenames. In *.log, * matches any number of characters; quotes leave interpretation to find. With ls logs/*.log, the shell expands * into matching filenames first. grep -n prints matching lines and their line numbers; here, you should see two ERROR entries. Use grep -F to search for a literal string, including characters such as the dot in notes.txt.
🛠 Narrow results with a pipeline
Commands normally write results to standard output, and programs can read text from standard input. A pipe, |, connects the output on the left to the input on the right, making it useful for combining filtering and selection.
grep -n 'ERROR' logs/app.log | tail -n 1
grep first keeps all error lines, then tail keeps the last one. Reversing the commands changes the meaning: running tail before grep searches only the selected portion. To search several logs at once, use grep -n 'ERROR' logs/*.log, provided that matching files exist.
🧰 Save a troubleshooting report
> writes standard output to a file, clearing any existing content. >> appends output to the end. The following commands create a new report and append another filtered result.
grep -n 'ERROR' logs/app.log > notes/error-report.txt
grep -n 'WARN' logs/app.log >> notes/error-report.txt
cat notes/error-report.txt
Do not write the report back to its source log: for example, grep ERROR logs/app.log > logs/app.log clears the source first. Programs usually write errors to standard error, a separate output channel. Later, you will use 2>&1 in scripts to combine the two streams.
❓ Knowledge check
Q1: Why does find need quotes around *.log?
Quotes let find apply the pattern while traversing directories. If the shell expands it first, find may receive specific names from the current directory instead.
Q2: Does no output from grep mean it read the wrong file?
There may simply be no match. Confirm the file path, then check the search term's capitalization. Use grep -i to ignore case if needed.
🧪 Exercise
Find the last ERROR in app.log, write it to notes/latest-error.txt, and locate the report with find notes -name 'latest-error.txt'. Check with cat: it should show one line containing startup port already in use.
🎉 You can now narrow a long log down to the line you need to investigate!
