This post discusses grep utility and provides Java code to search exceptions in a huge log file on a 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 a match to the given pattern. By default, grep prints the matching lines, but we can use the following 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, the following command will search for the string “Exception” in the log.txt file and output 10 lines from the match.

grep -A 10 "Exception" log.txt

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

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

We can also use the -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]

Solaris:

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 to /usr/local/bin/grep and /opt/csw/bin/grep locations.

2. On Windows

Windows don’t have to grep utility so that we can simplify things programmatically. Following Java program will read your log file line by line and search for the 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 the 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 the following commands:

javac Main.java
java -cp . Main

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

Download Code

Alternatively, you can also use the Grep4J library in Java to search exceptions in a log file. That’s all about searching exceptions in the huge log file.