Structured Logging With Timestamps
Emit log lines with a UTC timestamp, level, and message from one helper, so shell output stays consistent and easy to parse.
Code
#!/usr/bin/env bash
set -euo pipefail
LOG_LEVEL="${LOG_LEVEL:-info}"
declare -A LEVELS=([debug]=0 [info]=1 [warn]=2 [error]=3)
log() {
local level="${1:?level required}"
shift
local threshold="${LEVELS[${LOG_LEVEL}]:-1}"
local current="${LEVELS[${level}]:-1}"
if (( current < threshold )); then
return 0
fi
printf '{"timestamp":"%s","level":"%s","message":"%s"}\n' \
"$(date -u +%Y-%m-%dT%H:%M:%SZ)" "${level}" "$*" >&2
}
log info "job started"
log debug "this line is suppressed at info level"
log error "dependency unavailable"Report a problem with this exampleOpens a pre-filled issue on GitHub.