2 min read

Grep with context

Etienne Marais

Whether you are debugging an issue or monitoring a workload, log files are invaluable to your efforts. A normal strategy to look for a specific error or to find a certain piece of output is to cat <file> | grep something. This will output the lines of text that matches your grep argument.

cat laravel.log | grep "workload finished"

# Output
[2019-06-03 17:34:43] production.INFO: Backdating Partner[1] workload finished

Context

If you are looking to remedy an exception, you realise that there can be context attached to that error. Some Log writers allows you to pass a set of variables through or even a stacktrace to aid in your quest. This means that your grep will not show you that context by default.

grep --help

# Output
Usage: grep [OPTION]... PATTERN [FILE]...
Search for PATTERN in each FILE.
Example: grep -i 'hello world' menu.h main.c
...

Context control:
  -B, --before-context=NUM  print NUM lines of leading context
  -A, --after-context=NUM   print NUM lines of trailing context
  -C, --context=NUM         print NUM lines of output context

...

Luckily the creators of grep thought about this problem and provided us with a set of context controls.

cat laravel.log | grep -C 5 "workload finished"

# Output but with added context
[2019-06-03 17:34:39] production.INFO: Stats batched for 50 applications
[2019-06-03 17:34:41] production.INFO: Stats batched for 50 applications
[2019-06-03 17:34:42] production.INFO: Stats batched for 50 applications
[2019-06-03 17:34:42] production.INFO: Backdating Partner[1] with 9 leads
[2019-06-03 17:34:42] production.INFO: Backdating Partner[1] continues from Lead[12345]
[2019-06-03 17:34:43] production.INFO: Backdating Partner[1] workload finished
[2019-06-03 17:34:43] production.INFO: Stats batched for 50 applications
[2019-06-03 17:34:45] production.INFO: Stats batched for 50 applications
[2019-06-03 17:34:46] production.INFO: Stats batched for 50 applications
[2019-06-03 17:34:47] production.INFO: Stats batched for 50 applications
[2019-06-03 17:34:49] production.INFO: Stats batched for 50 applications

grep is part of the 5 basic commands in your unix arsenal. I would add awk, htop, df to that list as well.