Search exceptions in huge log file | grep utility & Java program

This post discusses about grep utility and provides java code to search exceptions in a huge log file on windows server.


1. On Unix Server

It is really frustrating when your code crashes in production. It is even more frustrating when you’re trying to search for an exception in a huge application log file(s). To simplify things, Linux has provided grep utility that searches files for a string or pattern and outputs the line that contains match to the given pattern. By default, grep prints the matching lines but we can use below options to change the default behavior.

grep [options] PATTERN [FILE...]

-A n
Print n lines of trailing context after matching lines.

-B n
Print n lines of leading context before matching lines.

-C n
Print n lines of output context.

Let’s start with -A option to solve our problem. grep -A n [pattern] [file] will output n lines from the [pattern] match in [file]. For example, below command will search for string “Exception” in log.txt file and output 10 lines from the match.

grep -A 10 "Exception" log.txt

For BSD or GNU grep, we can use -B option to set number of lines before the match and -A option to set number of lines after the match. For example, below command will print b lines before and a lines after the match

grep -B b -A a [pattern] [file]

We can also use -C option if we want the same number of lines before and after the match. To show n lines before and after the match, use

grep -C 3 [pattern] [file]


grep is part of the default installation on Solaris 11 in /usr/gnu/bin/grep. In Solaris 10, we can find GNU grep installed in /usr/sfw/bin/ggrep. The usage of ggrep is:

ggrep -A n [pattern] [file]

For older releases of Solaris, please refer /usr/local/bin/grep and /opt/csw/bin/grep locations.

2. On Windows

Windows doesn’t have grep utility so we can simplify things programmatically. Below java program will read your log file line by line and search for keyword “Exception” in each line. Once found, it will print the next 10 lines (exception trace) in a separate output file. Upon successful completion, you will have the output file with all exceptions listed out from the log file.

Please follow below steps to run the code –

Step 1: Update the code with full path of the log file.

Step 2: Run updated java program on eclipse or using command prompt by running below commands

java -cp . GetTrace

Please note that java should be set in your classpath or you can run these commands by giving full path of the executables (inside bin directory of JDK installation directory).


Hope this helps.

Please use ideone or C++ Shell or any other online compiler link to post code in comments.
Like us? Please spread the word and help us grow. Happy coding 🙂

Leave a Reply

Notify of