6

Is it possible to read log files (abc.log) using java?

I want a specific string from my log file.

suppose this is the content of my logfile. I want the time stamp only (eg: 05:08:37) and print it the console.

2012-12-16 05:08:37,905 [Thread-1] INFO  com.submit.SubmitService - Wait time 500

2012-12-16 05:08:38,444 [Thread-1] INFO  com.submit.SubmitService - NO OF  RECORDS TILL NOW 3755    TOTAL TIME -- << 539

2012-12-16 05:08:38,668 [Thread-1] INFO  com.submit.SubmitService - Active Connection:: -69076

2012-12-16 05:08:38,670 [Thread-1] INFO  com.submit.SubmitService - Active Connection:: -65764
Majid Laissi
  • 19,188
  • 19
  • 68
  • 105
smya.dsh
  • 651
  • 5
  • 10
  • 23
  • I tried with fileinputstream but it could not read .log extension. that's why i posted this question here. @pap it's not that i did not try anything.sometimes it happens that you know the solution but the idea doesn't come to your mind all of a sudden. – smya.dsh Dec 19 '12 at 05:13
  • I would try a scan delimiter using for example sc.useDelimiter(",|\r\n"); If that takes in too much of the file I would change it to use sc.useDelimiter(","); – DoesEatOats Aug 02 '18 at 15:15

2 Answers2

11

You can read your "log-file" as a normal file.

Then you can use, for instance, regular expression, to obtain the part of the string that you need:

try{
   FileInputStream fstream = new FileInputStream("abc.log");
   BufferedReader br = new BufferedReader(new InputStreamReader(fstream));
   String strLine;
   /* read log line by line */
   while ((strLine = br.readLine()) != null)   {
     /* parse strLine to obtain what you want */
     System.out.println (strLine);
   }
   fstream.close();
} catch (Exception e) {
     System.err.println("Error: " + e.getMessage());
}
Athif Shaffy
  • 692
  • 3
  • 10
  • 22
Luca Davanzo
  • 21,000
  • 15
  • 120
  • 146
  • 3
    How is this useful ? People don't learn when you just give out the answer, and it is clear that the OP hasnt tried *anything* – Hunter McMillen Dec 18 '12 at 14:17
  • my problem was that, i could not read .log extension.. i simply changed it to .txt and now it's working. thanks for your support. – smya.dsh Dec 19 '12 at 05:16
  • 2
    Please don't use DataInputStream to read text http://vanillajava.blogspot.co.uk/2012/08/java-memes-which-refuse-to-die.html – Peter Lawrey Jan 30 '13 at 20:49
0
import java.io.File;import java.io.FileNotFoundException;importjava.util.Scanner;
import java.sql.*;  

public class ReadingEntireFileWithoutLoop {

    public static void main(String[] args) throws FileNotFoundException {

        File file = new File("X:\\access.log");

        Scanner sc = new Scanner(file);
        sc.useDelimiter(",|\r\n");
        System.out.println(sc.next());
        while(sc.hasNext()){
            System.out.println(sc.next());
            }
            // closing the scanner stream
            sc.close();
    }
Nestor Milyaev
  • 5,845
  • 2
  • 35
  • 51
DoesEatOats
  • 625
  • 7
  • 13