如何将输出重新路由到具有时间戳的文件
How to reroute the output to a file with timestamp?
我在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
相关文章:
- 如何从远程 SFTP 服务器获取 HH-MM-SS 时间戳格式的文件列表
- 如何将消息时间戳写入日志文件?
- C++-需要读取存储在文件(.txt)中的时间戳并正确检索
- C++ 如何使用字符串中保存的文件路径创建带时间戳的目录
- 将时间戳添加到文本文件中的空行中
- 如何在C 中读取具有前缀和时间戳为文件名的文件
- C++如何获取文件最近更改的时间戳
- 从数据文件中解析时间戳并存储在矢量中
- Windows Batch - 如何在将标准输出重定向到文件时添加时间戳
- 将时间戳写入文件
- 保存文件或文件夹的时间戳
- 使用 WinHttp 函数检索 HTTP 文件的时间戳
- C++按时间戳对日志文件内容进行迭代
- 如何复制文件,但触摸新副本上的时间戳
- 编辑后保留文件的旧时间戳
- 正在从XML文件中提取时间戳
- 需要帮助诊断C++程序中的错误,该程序旨在从XML文件中提取时间戳
- C/ c++:读写时间戳数据到文件,支持多体系结构
- 文件中时间戳中的秒值有时会被舍入
- 创建一个标题中带有时间戳的文本文件