如何将输出重新路由到具有时间戳的文件

How to reroute the output to a file with timestamp?

本文关键字:时间戳 文件 路由 输出 新路由      更新时间:2023-10-16

我在Linux中有一个c++程序(二进制文件,我不能修改),它在标准输出中打印从其他程序获得的消息。所以,如果我运行这个程序,它会在标准输出中不时地打印消息。我通常会将输出重新路由到要读取的日志文件。program > & 1.log

示例1.log文件: message 1 message 2 message 3

问题是,这些消息没有时间戳。因此,我需要在1.log中打印带有接收时间的消息。

通缉表格: 07:12:08 211030 Message1 07:12:08 234630 Message1 07:12:08 254320 Message1

有人能告诉我怎么做吗?

您可以编写一个示例shell脚本来包装该程序,比如这个

program | while read msg; do
    date
    echo $msg
done

并将此脚本的输出重定向到日志文件。

如果您不喜欢date的默认输出,您可以通过添加适当的选项来更改其输出,有关更多详细信息,请参阅其手册date(1)

好吧,程序不经常刷新输出可能会有一些问题,所以时间戳可能比日志代码运行的时间晚,但你可以很容易地编写一个过滤器:

#include <iostream>
#include <iomanip>
#include <string>
#include <ctime>
int main()
{
    std::string line;
    while (getline(std::cin, line))
    {
         time_t seconds = time(NULL);
         struct tm datetime = *localtime(&seconds);
         std::cout << std::setw(2) << std::setfill('0') << datetime.tm_hour << ':'
                   << std::setw(2) << std::setfill('0') << datetime.tm_min << ':'
                   << std::setw(2) << std::setfill('0') << datetime.tm_sec << ' '
                   << line << 'n';
    }
}

然后,如果你把它编译成timestamper,那么调用你的程序如下:

program | timestamper >& 1.log

或者,使用awk:

program | awk '{ print strftime("%T"), $0 }' >& 1.log