DEV Community

Željko Šević
Željko Šević

Posted on • Originally published at sevic.dev on

1

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 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"
Enter fullscreen mode Exit fullscreen mode

Course

Build your SaaS in 2 weeks - Start Now

Image of Timescale

🚀 pgai Vectorizer: SQLAlchemy and LiteLLM Make Vector Search Simple

We built pgai Vectorizer to simplify embedding management for AI applications—without needing a separate database or complex infrastructure. Since launch, developers have created over 3,000 vectorizers on Timescale Cloud, with many more self-hosted.

Read more →

Top comments (0)

Image of Docusign

🛠️ Bring your solution into Docusign. Reach over 1.6M customers.

Docusign is now extensible. Overcome challenges with disconnected products and inaccessible data by bringing your solutions into Docusign and publishing to 1.6M customers in the App Center.

Learn more