为从标准输入接收的每一行添加时间戳
Prepend timestamp to each line received from stdin
您好,我正在尝试使用 bash 创建日志,但我得到的时间是错误的。我在后台 运行 这个。
# log code here before executing curl script log "Yay I was started"
curl https://example.com/process | sed "s/^/$(date -u) /" >> /path/to/logs.log &
处理c后设置的时间url是执行的时间,不是我得到响应后的时间。我需要得到响应后的时间。
这是示例输出(错误响应)
Fri Aug 21 01:43:12 UTC 2020 Yay I was started
Fri Aug 21 01:43:12 UTC 2020 Yay I was the response returned by the url
这里的 url https://example.com/process
休眠了 2 秒,但如您所见,执行时间和执行后我们得到响应的时间相同。
正确反应
Fri Aug 21 01:43:12 UTC 2020 Yay I was started
Fri Aug 21 01:43:14 UTC 2020 Yay I was the response returned by the url
我该如何解决这个问题?
您的问题是因为 sed "s/^/$(date -u) /"
在启动时捕获日期字符串并将其放在每行的开头。 curl
的响应中的每个传入新行都不会更新日期字符串。
使用 awk
而不是 sed
将日期添加到每一行之前更安全,因为它会为每一行捕获一个新日期。
您的原始日期格式是本地时间的区域设置格式。如果您愿意,它已保存在这里 as-is;但通常日志时间戳最好用 iso.org: ISO 8601 format 或 UTC 相对 Unix 时间戳打印。
curl https://example.com/process |
awk '{ printf("%s %s\n", strftime("%c", systime()), [=10=]) }' >>/path/to/logs.log &
使用 ISO-8601 时间戳:
curl https://example.com/process |
awk '{ printf("%s %s\n", strftime("%Y-%m-%dT%H:%M:%S%z", systime()), [=11=]) }' \
>>/path/to/logs.log &
请参阅 man strftime
了解时间格式。
您好,我正在尝试使用 bash 创建日志,但我得到的时间是错误的。我在后台 运行 这个。
# log code here before executing curl script log "Yay I was started"
curl https://example.com/process | sed "s/^/$(date -u) /" >> /path/to/logs.log &
处理c后设置的时间url是执行的时间,不是我得到响应后的时间。我需要得到响应后的时间。
这是示例输出(错误响应)
Fri Aug 21 01:43:12 UTC 2020 Yay I was started
Fri Aug 21 01:43:12 UTC 2020 Yay I was the response returned by the url
这里的 url https://example.com/process
休眠了 2 秒,但如您所见,执行时间和执行后我们得到响应的时间相同。
正确反应
Fri Aug 21 01:43:12 UTC 2020 Yay I was started
Fri Aug 21 01:43:14 UTC 2020 Yay I was the response returned by the url
我该如何解决这个问题?
您的问题是因为 sed "s/^/$(date -u) /"
在启动时捕获日期字符串并将其放在每行的开头。 curl
的响应中的每个传入新行都不会更新日期字符串。
使用 awk
而不是 sed
将日期添加到每一行之前更安全,因为它会为每一行捕获一个新日期。
您的原始日期格式是本地时间的区域设置格式。如果您愿意,它已保存在这里 as-is;但通常日志时间戳最好用 iso.org: ISO 8601 format 或 UTC 相对 Unix 时间戳打印。
curl https://example.com/process |
awk '{ printf("%s %s\n", strftime("%c", systime()), [=10=]) }' >>/path/to/logs.log &
使用 ISO-8601 时间戳:
curl https://example.com/process |
awk '{ printf("%s %s\n", strftime("%Y-%m-%dT%H:%M:%S%z", systime()), [=11=]) }' \
>>/path/to/logs.log &
请参阅 man strftime
了解时间格式。