views:

43

answers:

4

I have an application which generates logs in append mode, but the logs 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?

+2  A: 

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
martin clayton
hah. I forgot to tell that I am using Windows, and that I would like to avoid a Cygwin installation :) Thanks nonetheless!
Benoit
@Benoit - No worries - maybe retag? Someone will be along any minute with the Perl version.
martin clayton
the perl script is very good too… I wish I could accept more than one answer.
Benoit
+2  A: 

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}"
ghostdog74
That's great! I already have all binaries from UnxUtils and had not thought of gawk… thank you!
Benoit
download GNU tool from `gnuwin32.sourceforge.net/packages.html`. the ones from `UnxUtils` are outdated
ghostdog74
A: 

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(),"] $_";
}
OMG_peanuts
A: 

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

It may be worth a look.

Zaid