【问题标题】:Prepend timestamp to each line received from stdin为从标准输入接收到的每一行添加时间戳
【发布时间】:2020-08-24 11:05:32
【问题描述】:

您好,我正在尝试使用 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 &

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

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

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

https://example.com/process 此处的 url 休眠了 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

我该如何解决这个问题?

【问题讨论】:

    标签: bash timestamp stdin


    【解决方案1】:

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

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

    您的原始日期格式为本地时间格式。如果您愿意,它会按原样保存在这里;但通常日志时间戳最好使用iso.org: ISO 8601 format 或 UTC 相对 Unix 时间戳打印。

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

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

    【讨论】:

    • 这太棒了。我会接受这个作为答案,但我会有一个后续问题。如果我只需要每个 url 的响应而不是每行的 1 个日期/时间,这可能吗?谢谢。
    • @Defyleiti 每个 curl 请求只有一个时间戳前置:curl https://example.com/process | { printf '%s ' "$(date +%Y-%m-%dT%H:%M:%S%z)"; cat; } 或 bash 的内置 printf:curl https://example.com/process | { printf '%(%Y-%m-%dT%H:%M:%S%z)T '; cat; }
    猜你喜欢
    • 1970-01-01
    • 2020-02-04
    • 2017-02-25
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2013-02-23
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多