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"How the snippet works
set -euo pipefail removes the shell’s usual optimism — errors abort, empty variables abort, hidden pipeline failures abort.
The work is delegated to declare and log, chained so each stage’s output feeds the next.
A helper function (log) keeps the repeated logic out of the main flow.
The script leans on parameter expansion 5 times, using forms like ${var:-default} so defaults, trimming, and casing happen inside the shell with no external tool.
Statements that matter most here
"$(date -u +%Y-%m-%dT%H:%M:%SZ)" "${level}" "$*" >&2
Interactive Tools for This Topic
FAQ
- Does the script stop on the first error?
- Yes — `set -euo pipefail` aborts on the first failing command, treats unset variables as errors, and fails the whole pipeline if any stage fails. Nothing continues half-broken.
- Which external commands does the script rely on?
- `declare`, `log` must be available on the PATH environment variable; everything else is shell built-in syntax.
Report a problem with this exampleOpens a pre-filled issue on GitHub.