问题描述
嗨,我正在尝试使用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
的网址休眠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
来为每行添加日期是更安全的做法,因为它将为每行捕获一个新日期。
您的原始日期格式为语言环境格式,即本地时间。如果您愿意,它会保持原样。但是通常使用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",$0) }' \
>>/path/to/logs.log &
有关时间格式,请参见man strftime
。