为从标准输入接收的每一行添加时间戳 [英] Prepend timestamp to each line received from stdin

查看:38
本文介绍了为从标准输入接收的每一行添加时间戳的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

您好,我正在尝试使用 bash 创建日志,但是我得到的时间是错误的.我在后台运行它.

Hi there I'm trying to create logs using bash but the time I'm getting is wrong. I'm running this in background.

# 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 &

curl 处理后设置的时间是它执行的时间,而不是我得到响应后的时间.我需要得到响应后的时间.

The time set after processing curl is the time it was executed not the time after I got the response. I need to get the time after the response.

这是示例输出(错误响应)

Here's the sample output (Wrong response)

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 秒,但正如您所看到的,执行时间和执行后我们得到响应的时间相同.

The url here https://example.com/process sleeps for 2 seconds but as you can see the time is the same for when it was executed and after it we got the response.

正确回答

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

我该如何解决这个问题?

How can I solve this issue?

推荐答案

您的问题是因为 sed "s/^/$(date -u)/" 在时间它被启动并将其放置在每行的开头.不会为 curl 的响应中的每个传入新行更新日期字符串.

Your issue is because sed "s/^/$(date -u) /" captures the date string at the time it is launched and places it at the start of each line. The date string is not updated for each incoming new line from the curl's response.

使用 awk 而不是 sed 更安全,将日期添加到每一行,因为它会为每一行捕获一个新日期.

It is safer to use awk rather than sed, to prepend the date to each line, as it will capture a new date for each line.

您的原始日期格式是本地时间格式.如果您愿意,它已按原样保留在这里;但通常日志时间戳最好用 iso.org: I​​SO 打印8601 格式,或 UTC 相对 Unix 时间戳.

Your original date format is locale formatted, local time. It has been kept here as-is, if it is your preference; but usually logs timestamps are better printed with the iso.org: ISO 8601 format, or an UTC relative Unix timestamp.

curl https://example.com/process |
  awk '{ printf("%s %s\n", strftime("%c", systime()), $0) }' >>/path/to/logs.log &

带有 ISO-8601 时间戳:

With an ISO-8601 timestamp:

curl https://example.com/process |
  awk '{ printf("%s %s\n", strftime("%Y-%m-%dT%H:%M:%S%z", systime()), $0) }' \
    >>/path/to/logs.log &

有关时间格式,请参阅man strftime.

See man strftime for time formatting.

这篇关于为从标准输入接收的每一行添加时间戳的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆