从日志文件中读取数据作为单独的应用程序正在写入它

时间:2021-12-01 23:09:06

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.

我想监视应用程序正在写入的日志文件。我希望逐行处理文件,或者在写入之后不久。我还没有找到一种方法来检测文件在到达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.

代码需要在Mac和PC上运行,并且可以使用任何语言,尽管我最熟悉C ++和Perl。

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

有没有人建议最好的方法呢?

6 个解决方案

#1


7  

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

在Perl中,File :: Tail模块完全符合您的需要。

#2


3  

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.

EOF上的大多数语言都返回没有读取数据的语言。您可以在一段时间后重新尝试读取,如果文件已经增长,这次操作系统将返回数据。

#3


3  

The essense of tail -f is the following loop:

尾部-f的本质是以下循环:

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.

寻道呼叫是清除EOF标志。

#4


2  

You should be able to use read the standard io from tail -f

您应该能够使用tail -f中的标准io读取

#5


0  

I'd have thought outputting the actions via tee, and thence tail'ing (or using the loop above) the file created by tee some use.

我曾经想过通过tee输出动作,然后尾随(或使用上面的循环)由tee创建的文件。

#6


0  

For Java see this excellent article

对于Java,请参阅这篇优秀文章

http://www.informit.com/guides/content.aspx?g=java&seqNum=226

#1


7  

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

在Perl中,File :: Tail模块完全符合您的需要。

#2


3  

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.

EOF上的大多数语言都返回没有读取数据的语言。您可以在一段时间后重新尝试读取,如果文件已经增长,这次操作系统将返回数据。

#3


3  

The essense of tail -f is the following loop:

尾部-f的本质是以下循环:

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.

寻道呼叫是清除EOF标志。

#4


2  

You should be able to use read the standard io from tail -f

您应该能够使用tail -f中的标准io读取

#5


0  

I'd have thought outputting the actions via tee, and thence tail'ing (or using the loop above) the file created by tee some use.

我曾经想过通过tee输出动作,然后尾随(或使用上面的循环)由tee创建的文件。

#6


0  

For Java see this excellent article

对于Java,请参阅这篇优秀文章

http://www.informit.com/guides/content.aspx?g=java&seqNum=226