1

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?

brian d foy
  • 129,424
  • 31
  • 207
  • 592
Benoit
  • 76,634
  • 23
  • 210
  • 236

4 Answers4

2

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
  • 76,436
  • 32
  • 213
  • 198
  • hah. I forgot to tell that I am using Windows, and that I would like to avoid a Cygwin installation :) Thanks nonetheless! – Benoit Oct 20 '10 at 09:48
  • @Benoit - No worries - maybe retag? Someone will be along any minute with the Perl version. – martin clayton Oct 20 '10 at 09:52
  • the perl script is very good too… I wish I could accept more than one answer. – Benoit Oct 20 '10 at 09:59
  • To avoid the `echo` with backticks, you can pass the `$line` as an argument to `date`: `date +"%c $line"` (provided your `$line` doesn't contain percent codes which `date` would interpret as formatting instructions). – tripleee May 10 '12 at 04:50
2

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
  • 327,991
  • 56
  • 259
  • 343
  • That's great! I already have all binaries from UnxUtils and had not thought of gawk… thank you! – Benoit Oct 20 '10 at 09:55
  • 2
    download GNU tool from `gnuwin32.sourceforge.net/packages.html`. the ones from `UnxUtils` are outdated – ghostdog74 Oct 20 '10 at 10:03
  • I used it to update the telnet logs with time-stamp, but the gawk is not appending the timestamp. C:\tail.exe -F "C:\Test.txt" | C:\gawk.exe "{s=systime(); print strftime(\"%Y-%m-%d:%H:%M:%S\",s),$0}" – buddy Feb 07 '14 at 05:38
1

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
  • 1,797
  • 1
  • 13
  • 19
0

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

It may be worth a look.

Zaid
  • 36,680
  • 16
  • 86
  • 155