如何将控制台打印记录到带有时间戳的文件中

时间:2013-11-20 16:07:45

标签: linux logging time cpu-time

使用xxx> log,我们可以将所有控制台打印到日志文件中。

虽然如何为每张照片获取时间戳?

由于

1 个答案:

答案 0 :(得分:1)

构建一个脚本,将输入行回显到stdout,预先设置时间戳。你可以使用shell / bash,perl,python,ruby,C,awk等(任何读写stdio,并获得格式化日期的东西),

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

例如,

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

首选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";
}

红宝石怎么样?

#!/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

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;

和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);
    }
}

有人想提供awk版本吗?