Skip site navigation (1)Skip section navigation (2)
Date:      Mon, 19 May 2003 16:07:38 +0300
From:      Giorgos Keramidas <keramida@ceid.upatras.gr>
To:        Andy Farkas <andyf@speednet.com.au>
Cc:        freebsd-questions@freebsd.org
Subject:   Re: timestamping a text stream
Message-ID:  <20030519130738.GE5081@gothmog.gr>
In-Reply-To: <20030519113017.GA46308@zi025.glhnet.mhn.de>
References:  <20030519174723.B93323-100000@hewey.af.speednet.com.au> <20030519113017.GA46308@zi025.glhnet.mhn.de>

next in thread | previous in thread | raw e-mail | index | archive | help
On 2003-05-19 13:30, Simon Barner <barner@in.tum.de> wrote:
>Andy Farkas <andyf@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



Want to link to this message? Use this URL: <https://mail-archive.FreeBSD.org/cgi/mid.cgi?20030519130738.GE5081>