timestamping a text stream

Giorgos Keramidas keramida at ceid.upatras.gr
Mon May 19 06:26:03 PDT 2003


On 2003-05-19 13:30, Simon Barner <barner at in.tum.de> wrote:
>Andy Farkas <andyf at speednet.com.au> wrote:
>> Does anybody know of a program similar to script(1) or tee(1) that
>> will timestamp each line of input as it happens?
>
> You can use this perl script:
>
> #!/usr/bin/perl -w
> # This is timestamp.pl
>
> use strict;
>
> my $line=undef;
> my $stamp;
> while (defined ($line = <>)) {
> 	$stamp = localtime (time ());
> 	print ("$stamp: $line");
> }

Or alternatively, for even more detail in the logs (namely subsecond
accuracy in the timestamps), you can use gettimeofday() instead of
localtime():

    #!/usr/bin/perl -wT

    use POSIX qw(strftime);
    require 'sys/syscall.ph';

    $| = 1;

    $TIMEVAL_T = "LL";

    while (defined($line = <STDIN>)) {
        $now = pack($TIMEVAL_T, ());
        syscall(&SYS_gettimeofday, $now, 0) != -1
            or die "gettimeofday: $!";
        @now = unpack($TIMEVAL_T, $now);
        $ts = strftime("%Y.%m.%d.%H.%M.%S.", localtime($now[0])) .
            sprintf("%06d", $now[1]);
        chomp $line;
        print "$ts| $line\n";
    }

The time() call of libc will call gettimeofday() anyway in FreeBSD, and
strip the subsecond data returned by that system call, so you might as
well call gettimeofday() directly :)

- Giorgos



More information about the freebsd-questions mailing list