开发者

How can I monitor a log file and insert timestamps, using Perl?

I have an application which generates logs in append mode, but the l开发者_开发百科ogs are not timestamped.

Is it possible to use tail -f with some option, or a perl script to monitor writes to this file and prefix them with a timestamp?

Given that I am running Windows without Cygwin, could I avoid using bash or any other Unix shell?


if you are using GNU tail, then you should be able to use GNU gawk.

C:\test>tail -F file  | gawk.exe "{s=systime(); print strftime(\"%Y-%m-%d:%H:%M:%S\",s),$0}"


You could use a while loop:

tail -f logfile | while read line;
do
    echo $(date) $line;
done

Implies running date for each line though. You could use the format output options of the date command to get the timestamp format you want.

I very basic Perl equivalent would be (script.pl):

while (<>) {
    my $date = scalar localtime;
    print $date . " " . $_;
}

tail -f logfile | perl script.pl


May be could you use a perl script with File::Tail and DateTime ?

use File::Tail;
use DateTime;
my $ref=tie *FH,"File::Tail",(name=>$ARGV[0]);
while (<FH>) {
    my $dt = DateTime->now();
    print "[", $dt->dmy(), " ",$dt->hms(),"] $_";
}


It looks like the File::Tail module was designed specifically for reading in appended log files.

It may be worth a look.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜