perl的File::Tail模块

      use File::Tail;

      功能:读取不断变化的文件,相当于tail -f file 命令
      eg:
           (1) $file = File::Tail->new(name=>$logfile, tail=>-1);           
                 while
( defined($line=$file->read) )  {
                           print
"$line";
                 }
          (2)
my$ref=tie*FH,"File::Tail",(name=>$name);

                while () { print "$_";}
Note that the above script will never exit. If there is nothing being written to the file, it will simply block.
注意:上面例子不会退出,如果没有一个向file写的程序,它讲一直阻塞
You can find more synopsii in the file logwatch, which is included in the distribution.
Note: Select functionality was added in version 0.9, and it required some reworking of all routines. ***PLEASE*** let me know if you see anything strange happening.You can find two way of using select in the file select_demo which is included in the ditribution.

DESCRIPTION:描述
The primary purpose of File::Tail is reading and analysing log files while they are being written, which is especialy usefull if you are monitoring the logging process with a tool like Tobias Oetiker's MRTG.
File::Tail最主要的目的是读取和分析log文件,如果你想用像MRTG工具监听一个日志文件进程来绘图,这个方式是非常有用的。

The module tries very hard NOT to "busy-wait" on a file that has little traffic. Any time it reads new data from the file, it counts the number of new lines, and divides that number by the time that passed since data were last written to the file before that. That is considered the average time before new data will be written. When there is no new data to read,File::Tail sleeps for that number of seconds. Thereafter, the waiting time is recomputed dynamicaly. Note thatFile::Tail never sleeps for more than the number of seconds set by maxinterval.
这个模块很忙并不是“忙等待”文件,任何时候当他从文件中读取了新数据,他会记录新行的个数并按时间(最近一次写入和之前的时间)把数据分开。

If the file does not get altered for a while, File::Tail gets suspicious and startschecking if the file was truncated, or moved and recreated. If anything like that had happened,File::Tail will quietly reopen the file, and continue reading. The only way to affect what happens on reopen is by setting the reset_tail parameter (see below). The effect of this is that the scripts need not be aware when the logfiles were rotated, they will just quietly work on.
当模块在一段时间内没有获取到文件的变化,File::Tail将怀疑并且开始检查文件是否有被删减或者移动或者重建的状况。如果发上上述情况,File::Tail便默默地重新打开文件继续读取。对重新打开的唯一影响是打开文件的设置参数,脚本会按参数设置默默的打开文件继续工作。

Note that the sleep and time used are from Time::HiRes, so this module should do the right thing even if the time to sleep is less than one second.
注意sleep和时间应用的是Time::HiRes模块,所以即使睡眠时间小于1秒钟也需要用这个模块。

The logwatch script (also included) demonstrates several ways of calling the methods.

CONSTRUCTOR:参数
   new([ argv ]):
creates a File::Tail. If it has only one paramter, it is assumed to be the filename. If the open fails, the module performs a croak. I am currently looking for a way to set $! and return undef.
创建一个File::Tail,如果仅有一个参数,该参数默认是被监听的文件名,如果打开失败会产生一个错误,我目前还在寻找一种方式去设置$!并返回未定义。

name:名字
This is the name of the file to open. The file will be opened for reading. This must be a regular file, not a pipe or a terminal (i.e. it must be seekable).
指定以读方式打开文件的文件名,该文件必须是常规文件,不可以是管道文件或终端。
maxinterval:最大间隔
The maximum number of seconds (real number) that will be spent sleeping. Default is 60, meaning File::Tail will never spend more than sixty seconds without checking the file.
睡眠时间的最大间隔数,默认是60秒,也就是说读取新的文件数据之间的间隔不超过60秒。
interval:间隔
the initial number of seconds (real number) that will be spent sleeping, before the file is first checked. Default is ten seconds, meaning File::Tail will sleep for 10 seconds and then determine, how many new lines have appeared in the file.
默认的间隔是10秒读一次。   adjustafter: The number of times File::Tail waits for the current interval, before adjusting the interval upwards. The default is 10.
resetafter:
The number of seconds after last change when File::Tail decides the file may have been closed and reopened. The default is adjustafter*maxinterval.

maxbuf:
The maximum size of the internal buffer. When File::Tail suddenly found an enormous ammount of information in the file (for instance if the retry parameters were set to very infrequent checking and the file was rotated), File::Tail sometimes slurped way too much file into memory. This sets the maximum size of File::Tail's buffer。
Default value is 16384 (bytes).
A large internal buffer may result in worse performance (as well as increased memory usage), since File::Tail will have to do more work processing the internal buffer.

nowait:
Does not block on read, but returns an empty string if there is nothing to read. DO NOT USE THIS unless you know what you are doing. If you are using it in a loop, you probably DON'T know what you are doing. If you want to read tails from multiple files, use select.

ingore_nonexistant:
Do not complain if the file doesn't exist when it is firstopened or when it is to be reopened. (File may be reopened after resetafter seconds have passed since last data was found.)

tail:
When first started, readand return C lines from the file. If C is zero, start at the end of file. If C is negative,return the whole file.

reset_tail:
Same as tail, but applies after reset.(i.e. after thefile has been automaticaly closedand reopened). Defaults toC<-1>,i.e. does not skip any information present in thefile when it first checks it. Why would you want it otherwise? I've seen files whichhave been cycled like this:grep -v lastmonth log >newlog mv log archive/lastmonth mv newloglog kill -HUP logger。

Obviously, if this happens and you have reset_tail set to c<-1>, you will suddenly get a whole bunch of lines - lines you already saw. So in this case, reset_tail should probably be set to a small positive number or even0.

name_changes:
Some logging systems change the name of the file they are writing to, sometimes to include a date, sometimes a sequence number, sometimes other, even more bizarre changes.
Instead of trying to implement various clever detection methods, File::Tail will call the code reference defined in name_changes. The code reference should return the string which is the new name of the file to try opening.
Note that if the file does not exist, File::Tail will report a fatal error (unless ignore_nonexistant has also been specified).

debug:
Set to nonzero if you want to see more about the inner workings of File::Tail. Otherwise not useful.

errmode:
Modeled after the methods from Net:Telnet, here you decide how the errors should be handled. The parameter can be a code reference which is called with the error string as a parameter, an array with a code reference as the first parameter and other parameters to be passed to handler subroutine, or one of the words:
return - ignore any error (just put error message in errmsg). warn - output the error message but continue die - display error message and exit
Default is die.

METHODS:方法
read:read returns one line from the input file. If there are no lines ready, it blocks until there are.
read从输入的文件中返回一行,如果已经没有数据了,阻塞。

select:select is intended to enable the programmer to simoultaneously wait for input on normal filehandles and File::Tail filehandles. Of course, you may use it to simply read from more than one File::Tail filehandle at a time. Basicaly, you call File::Tail::select just as you would normal select, with fields for rbits, wbits and ebits, as well as a timeout, however, you can tack any number of File::Tail objects (not File::Tail filehandles!) to the end。
select是使程序员能够同时监听普通的文件句柄和File::Tail打开的文件句柄。当然你也可以用它同时从多个File::Tail打开的文件句柄度信息。当然你要用File::Tail::select加上读、写、ebits或者也可以设置超时参数打开才行,你可以附加许多File::Tail目标(不是File::Tail句柄)。

Usage example:
           foreach(@ARGV){
                    push(@files, File::Tail->new(name=>"$_",debug=>$debug));
           }
          
while (1){
                  
 ($nfound,$timeleft,@pending)= File::Tail::select(undef,undef,undef,$timeout,@files);
                    
unless ($nfound) {
                               
# timeout - do something else here, if you need to
                     } 
                     else {
                              
 foreach (@pending){
                                          
 print$_->{"input"}." (".localtime(time).") ".$_->read;

                     }
           
}
When you do this, File::Tail's select emulates normal select, with two exceptions:

a) it will return if there is input on any of the parameters (i.e. normal filehandles) _or_ File::Tails.

b) In addition to ($nfound, $timeleft), the return array will also contain a list of File::Tail objects which are ready for reading.$nfound will contain the correct number of filehandles to be read (i.e. both normal and File::Tails).
除了($nfound,$timeleft)之外,返回的数组也会包含一个File:Tail目标的列表,他们已经准备好被读取了。$nfound,包含了正确的用来读句柄数。

Once select returns, when you want to determine which File::Tail objects have input ready, you can either use the list of objects select returned, or you can check each individual object with $object->predict. This returns the amount of time (in fractional seconds) after which the handle expects input. If it returns 0, there is input waiting. There is no guarantee that there will be input waiting after the returned number of seconds has passed. However, File::Tail won't do any I/O on the file until that time has passed. Note that the value of $timeleft may or may not be correct - that depends on the underlying operating system (and it's select), so you're better off NOT relying on it.
一旦select返回,当你想知道哪个File::Tail目标有输入准备,你可以试试object select的返回列表,或者可以用$object->predict检查每个object。他返回过多少时间之后处理预计输入。如果返回0说明等待输入。不能保证返回秒数时这个时间已经过去。然而,File::Tail不会有任何的I/O作用在文件上直到时间到了。注意$timeleft的值也可能不正确——它取决于操作系统,所以你做好不要依赖它。
Also note, if you are determining which files are ready for input by calling each individual predict, the$nfound value may be invalid, because one or more of File::Tail object may have become ready between the time select has returned and the time when you checked it.
注意,如果你根据$object->predict知道了哪个文件准备好输入,$nfound变量可能是无效的,因为在select 和查询期间可能一个或者更多的File::Tail目标准备好了。

 

 

 

 

 

 

 

你可能感兴趣的:(scripts)