Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Reading data from a log file as a separate application is writing to it

I would like to monitor a log file that is being written to by an application. I want to process the file line by line as, or shortly after, it is written. I have not found a way of detecting that a file has been extended after reaching eof.

The code needs to work on Mac and PC, and can be in any language, though I am most familiar with C++ and Perl.

Does anybody have a suggestion for the best way to do it?

like image 696
David Sykes Avatar asked Sep 15 '08 13:09

David Sykes


3 Answers

In Perl, the File::Tail module does exactly what you need.

like image 62
David Precious Avatar answered Oct 15 '22 17:10

David Precious


A generic enough answer:

Most languages, on EOF, return that no data were read. You can re-try reading after an interval, and if the file has grown since, this time the operating system will return data.

like image 3
tzot Avatar answered Oct 15 '22 19:10

tzot


The essense of tail -f is the following loop:

open IN, $file;
while(1) {
  my $line = <IN>;
  if($line) {
    #process line...
  } else {
    sleep(1);
    seek(IN,0,1);
  }
}
close IN;

The seek call is to clear the EOF flag.

like image 3
Bruno De Fraine Avatar answered Oct 15 '22 17:10

Bruno De Fraine