Attach timestamp to each line of stdout

5,045

Solution 1

Create a bash script as the following:

#!/bin/bash

while read -r line; do
        timestamp=`date`
        echo "[$timestamp] $line"
done

Call it relog.sh and set it as executable issuing chmod +x relog.sh Then you can pipe through it and it will print a timestamp followed by the original log line. For example, issuing cat /etc/services | ./relog.sh will produce an output similar to this:

[Wed Oct 28 22:34:25 CET 2015] netmap_lm       1493/tcp                # netmap_lm
[Wed Oct 28 22:34:25 CET 2015] netmap_lm       1493/udp                # netmap_lm
[Wed Oct 28 22:34:25 CET 2015] cvc             1495/tcp                # cvc
[Wed Oct 28 22:34:25 CET 2015] cvc             1495/udp                # cvc

Please note that the above script is only a stub; you can (must?) complete it as per your needs.

Solution 2

This could be much faster than a bash script but basically does the same thing.

#!/usr/bin/perl

# Print each line of stdin
while() {
        # Grab the current time
        my @now = localtime();

        # Rearrange the following to suit your stamping needs.
        # it currently generates YYYYMMDDhhmmss
        my $timeStamp = sprintf("%04d%02d%02d%02d%02d%02d",
                        $now[5]+1900, $now[4]+1, $now[3],
                        $now[2],      $now[1],   $now[0]);

        print ($timeStamp, " $_");
}

Execute as

yourapp | thisscript.pl

Example

$ ./a | ./stdout.pl 
20151028200508 test
20151028200509 test2
Share:
5,045

Related videos on Youtube

kodisha
Author by

kodisha

I love art, programming and music... :) read more on my blog :)

Updated on September 18, 2022

Comments

  • kodisha
    kodisha over 1 year

    Im am hosting some game servers, and each server instance runs in stdout, but they don't have timestamps, just logging events to new lines, e.g.:

    • player a connected
    • player b connected
    • game started
    • player X fragged player Y
    • game ended

    etc.

    The problem with this is that when the server crashes I have no idea when did that happen.

    Is there a way to pipe servers stdout trough some command, and get the same output back to file, or stdout again, but with timestamp in front???