Bugs in a production environment are stressful. The search for context information typically starts by searching the log files. It can be tedious to find the context you’re looking for in (rotated) log files or you’re pushing a large amount of data to your logs.
A nice thing about grep is that it can search for a pattern in multiple files at the same time. Simultaneously search in selected files or use a glob pattern that resolves all files for you. This tutorial shows you how to search in multiple log files using grep.
Ubuntu/Debian Series Overview
- Fix “sudo command not found”
- Install a Specific Version with apt-get on Ubuntu/Debian
- Fix Ubuntu/Debian apt-get “KEYEXPIRED: The following signatures were invalid”
- How to Test a Cron Job
- How to Unzip Into a Folder
- How to Show Your Elasticsearch Version on Ubuntu/Debian
- Use “which” in Linux to find the Location of an Exetable
- Sort “ls” by Last Changed Date
- How to Shutdown a Machine
- Show Hidden Files and Folders with `ls`
- Case Insensitive Search
- Search Recursive in Subdirectories
- Search all Files in a Directory (Non-Recursively)
- Search in Multiple Log Files
Search in Selected Log Files with grep
grep allows you to search for a pattern in more than one file. You may search in selected log files if your application sends logs to different files. For example, you may search your default app.log
and an extra delete-audit.log
file. Add your selected files as separate arguments to grep:
grep "pattern" storage/logs/app.log storage/logs/delete-audit.log
Search in all .log
Files with grep
You can also use a glob pattern to search within all files having the .log
file extension. The following line searches for the given pattern in all log files within the storage/logs
directory. It won’t search through subdirectories and stay on the selected directory’s level to pick the files:
grep "pattern" storage/logs/*.log
Examples
Here’s a sample output of how grep prints the matches to the console. Notice that a matching line is printed with the prefixed log file name. This helps you detect what log file could have more details:
$ grep "request" storage/logs/*.log
storage/logs/app.log:INFO: ======= request finished successful ======> {"took":"0.052s","status_code":200}
storage/logs/delete-audit.log:DEBUG: User deletion requested {"userId":"1"}
storage/logs/delete-audit.log:DEBUG: User successfully deleted {"userId":"1"}
That’s it!