JSON logging bash scripts
Logs are usually streamed to the standard output in JSON format so logging aggregators (Graylog, e.g.) can collect and adequately parse them.
The following example shows how bash script output can be formatted with the message, log levels, and timestamp. Error logs are streamed into a temporary file, formatted, and redirected to the standard output.
#!/usr/bin/env bashdeclare -A log_levels=( [FATAL]=0 [ERROR]=3 [WARNING]=4 [INFO]=6 [DEBUG]=7)json_logger() {log_level=$1message=$2level=${log_levels[$log_level]}timestamp=$(date --iso-8601=seconds)jq --raw-input --compact-output \'{"level": '$level',"timestamp": "'$timestamp'","message": .}'}{set -eecho $? 1>&2echo "Finished"} 2>/tmp/stderr.log | json_logger "INFO"cat /tmp/stderr.log | json_logger "ERROR"