homeresume
 
   
🔍

JSON logging bash scripts

March 18, 2022

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 bash
declare -A log_levels=( [FATAL]=0 [ERROR]=3 [WARNING]=4 [INFO]=6 [DEBUG]=7)
json_logger() {
log_level=$1
message=$2
level=${log_levels[$log_level]}
timestamp=$(date --iso-8601=seconds)
jq --raw-input --compact-output \
'{
"level": '$level',
"timestamp": "'$timestamp'",
"message": .
}'
}
{
set -e
echo $? 1>&2
echo "Finished"
} 2>/tmp/stderr.log | json_logger "INFO"
cat /tmp/stderr.log | json_logger "ERROR"