Monday, October 12, 2015

Java Log Helper using Scanner

Problem Statement: 
Sometimes it becomes very tedious to find some thing in a huge log file, most of the time we look for some string pattern in the log file, For example we look for keywords like "success", "failure", "error", "warning", "java stack trace", "error code" , etc.
Through  this utility, without opening the log file and effortlessly  we can find the string we are looking for within the log file. If there is a match the utility will return a match along with the line numbers the string you are looking for is present.
From the sample.txt file I am finding the string "com0113:



OUTPUT



 package sudas.utils;  
 import java.io.BufferedInputStream;  
 import java.io.File;  
 import java.io.FileInputStream;  
 import java.io.FileNotFoundException;  
 import java.io.IOException;  
 import java.util.Scanner;  
 public class LogScannerHelper {  
      public static void main(String[] args) {  
           // new Bufferedreader().inputStream();  
           new scanner().scanLines();  
      }  
 }  
 class scanner {  
      // read the content of the log file and search for a perticular string  
      public void scanLines() {  
           try {  
                Scanner scan = new Scanner(new File("C:/Test/sudas.txt"));  
                String match = "of";  
                int lineNumber = 1;  
                while (scan.hasNextLine()) {  
                     String line = scan.nextLine();  
                     // System.out.println(line+'\t'+lineNumber++);  
                     Scanner string = new Scanner(line);  
                     String completeString = string.findInLine("companies");  
                     {  
                          int lineNum = lineNumber++;  
                          if (completeString != null) {  
                               System.out.println(completeString + '\t' + "-- at line number "+lineNum);  
                          }  
                     }  
                }  
           } catch (FileNotFoundException e) {  
                // TODO Auto-generated catch block  
                e.printStackTrace();  
           }  
      }  
 }  

No comments:

Post a Comment