2

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???

1
3

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.

1

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
0

Use ts command from moreutils (apt get moreutils).

 $ ls -1 | ts

Oct 12 20:09:27 ts-out.v37mPS
Oct 12 20:09:27 ts-out.vavMYs
Oct 12 20:09:27 ts-out.wd9G1Y
Oct 12 20:09:27 ts-out.ym8aN0
Oct 12 20:09:27 ts-out.zCzWhY

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.