Home > Software Development > How to Monitor New Changes of Log File with Java

How to Monitor New Changes of Log File with Java

October 30th, 2013 Leave a comment Go to comments

If you have a log file that you want to monitor the incremental changes, you can use the following simple code. Whatever new log entries written to the log will be quickly picked up and printed out to console. It does not interfere with the application that writes the log file. To test the code, you can use any text editor to append more entries to the end of log file (don’t forget to save it).

Although it can be used for monitoring log, it does not mean it’s limited with log file only. You can use the code to monitor any other text files that grow incrementally. For this characteristics, a log file is for sure the best sample.

Time to learn how to "Google" and manage your VMware and clouds in a fast and secure

HTML5 App

What if you shrink the content of your text file? You won’t be able to read more content until you grow over where was read before.

This simple code uses waiting a short period of time before next read. You can change it to event driven so that changes are read immediately after being written. For the output, there are even more options like posting it to messaging system, saving it to a database, etc.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
import java.io.BufferedReader;
import java.io.FileReader;
 
/**
 * @author Steve Jin (http://www.doublecloud.org)
 */
public class LogMonitor 
{
  public static void main(String[] args) throws Exception
  {
    FileReader fr = new FileReader("c:/temp/logSample/test.log");
    BufferedReader br = new BufferedReader(fr);
 
    while (true) 
    {
      String line = br.readLine();
      if (line == null)
      {
        Thread.sleep(1*1000);
      } 
      else
      {
        System.out.println(line);
      }
    }
  }
}
Categories: Software Development Tags: ,
  1. pedro
    March 6th, 2015 at 17:15 | #1

    Thanks Steve, i thought of using JRE 7 RandomAccessFile to get a file pointer but your solution is indeed way more cleaver and simpler.

  1. No trackbacks yet.