gpt4 book ai didi

bash - 格式化shell脚本日志并写入文件

转载 作者:行者123 更新时间:2023-12-04 16:17:15 44 4
gpt4 key购买 nike

我需要将 shell 脚本中的所有输出/错误日志记录到具有标准格式的文件中。
例如对于文件 script.sh:

echo "I want to be a json message!"
echo "I also want to be a json message!"
执行如下:
./script.sh >> jsonmessages.log
应该给我一个文件内容,如:
{timestamp: '2020-12-31 00:00:00', message: 'I want to be a json message!'}
{timestamp: '2020-12-31 00:00:00', message: 'I also want to be a json message!'}

最佳答案

将 shell 字符串可靠地转换为有效的 JSON 字符串的最佳选择是使用 JSON 解析器/格式化程序。最受欢迎的是jq .
这是一个使用 jq 的带时间戳的 JSON 消息记录器的实现。 :

#!/usr/bin/env bash

json_logger() {
while read -r msg || [ -n "$msg" ]; do
jq \
-nc \
--arg msg "$msg" \
'{ "timestamp": (now | strftime("%Y-%m-%d %H:%M:%S")), "message": $msg }'
done
}


----------


编辑:
KamilCuk写道:

We can do better without slow bash loop - it's just jq --raw-input '{ "timestamp": (now | strftime("%Y-%m-%d %H:%M:%S")), "message": . }'


所以这里是一个改进的 json_logger :
json_logger() {
jq \
--raw-input \
--compact-output \
'{ "timestamp": (now | strftime("%Y-%m-%d %H:%M:%S")), "message": . }'
}

附录:
Harshit Kushwaha wrote :

For example, I need to print the method name in json from where the json_logger was called. How can I modify the json_logger and how to use it then in echo?


如果作为参数提供给 json_logger,这是一个添加方法名称的实现。功能:
#!/usr/bin/env bash

IFS= read -r -d '' __JQ_LOGGER_SCRIPT <<'JQSCRIPT'
{
"timestamp": now | strftime("%Y-%m-%d %H:%M:%S"),
"message": .
} |
if ($name | length) != 0
then
. + { "method": $name }
else
.
end
JQSCRIPT

json_logger() {
jq \
--raw-input \
--compact-output \
--arg name "$1" \
"$__JQ_LOGGER_SCRIPT"
}

echo "I want to be a json message!" | json_logger
echo "I also want to be a json message!" | json_logger echo

printf %s $'I am a message with "quoted text" and some special characters: \'\t\7\42\\\'; that can only be properly converted to JSON with a JSON formatter and parser.' | json_logger printf
生成此 JSON 输出:
{"timestamp":"2021-01-29 14:02:46","message":"I want to be a json message!"}
{"timestamp":"2021-01-29 14:02:46","message":"I also want to be a json message!","method":"echo"}
{"timestamp":"2021-01-29 14:02:46","message":"I am a message with \"quoted text\" and some special characters: '\t\u0007\"\\'; that can only be properly converted to JSON with a JSON formatter and parser.","method":"printf"}

关于bash - 格式化shell脚本日志并写入文件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/65827333/

44 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com