0

With xxx > log, we can get all console prints into the log file.

While how can I get a timestamp for each prints?

Thanks

thundium
  • 995
  • 4
  • 12
  • 30

1 Answers1

1

Build a script that echoes input lines to stdout, prepending a timestamp. You can use shell/bash, perl, python, ruby, C, awk, etc (anything that read and write stdio, and get a formatted date),

#!/usr/bin/bash
#loggy.sh
while read line
do
    now=$(/bin/date +%y%m%d%H%M%S)
    echo $now $line
end

example,

echo "hello, world" | ~/loggy.sh

Prefer perl?

#!/bin/env perl
use strict;
use warnings;
#loggy - log a line, prepend date

while(my $line=<>)
{
    my $now=`/bin/date +%y%m%d%H%M%S`; chomp($now);
    print "$now: $line";
}

How about ruby?

#!/bin/env ruby
#loggy - log a line, prepend date
require 'date'
while( line = gets ) do
    now=Time.new().utc().strftime("%y%m%d%H%M%S")
    print "#{now}: #{line}";
end

How about python?

#!/bin/env python
#loggy - log a line, prepend date
#see: http://docs.python.org/2/library/datetime.html
from datetime import datetime

#do you prefer fileinput or sys?
#import fileinput
#for line in fileinput.input():
#    now=datetime.now()
#    print now.strftime("%y%m%d%H%M%S"), ": ", line;

import sys
for line in sys.stdin:
    now=datetime.now()
    print now.strftime("%y%m%d%H%M%S"), ": ", line;

And C,

#include <stdio.h>
#include <time.h>       //strftime, time_t time() to second resolution
#include <sys/time.h>   //gettimeofday, microsecond resolution
//size_t strftime(char *s, size_t max, const char *format, const struct tm *tm);
//int gettimeofday(struct timeval *tv, struct timezone *tz);
//use reentrant versions,
//struct tm *gmtime_r(const time_t *timep, struct tm *result);
//struct tm *localtime_r(const time_t *timep, struct tm *result);

int main()
{
    char buffer[4096];  //largest log entry
    char datestr[64];   //space for %t%m%d%H%M%S datetimestamp
    time_t prev=0;
    //struct timeval tv;
    time_t tx;
    struct tm nowtm;
    while(fgets(buffer,sizeof(buffer),stdin))
    {
        tx = time(NULL);
        //or, microsecond resolution
        //gettimeofday(&tv,NULL);
        if(tx != prev)
        {
        strftime(datestr,sizeof(datestr),"%y%m%d%H%M%S",gmtime_r(&tx, &nowtm));
        //strftime(datestr,sizeof(datestr),"%y%m%d%H%M%S",localtime_r(&tx, &nowtm));
        prev = tx;
        }
        printf("%s: %s",datestr,buffer);
    }
}

Anybody want to provide an awk version?

ChuckCottrill
  • 4,360
  • 2
  • 24
  • 42