Skip to content
GreenSnippets

Timestamped logging functions for scripts

Small log, warn and die helpers that write ISO timestamps to stderr and keep stdout clean for data.

Bash
log()  { printf '%s [INFO]  %s\n' "$(date -u +%FT%TZ)" "$*" >&2; }
warn() { printf '%s [WARN]  %s\n' "$(date -u +%FT%TZ)" "$*" >&2; }
die()  { printf '%s [ERROR] %s\n' "$(date -u +%FT%TZ)" "$*" >&2; exit 1; }

Example / expected output

Output
log "Starting backup"
[[ -d /data ]] || die "/data does not exist"
<!-- 2025-03-01T10:15:00Z [INFO]  Starting backup -->

How it works

Writing logs to stderr keeps stdout usable for piping results. date -u +%FT%TZ gives an ISO 8601 UTC timestamp that sorts correctly and is unambiguous across machines. die logs and exits with a non-zero status so callers and CI notice.

This snippet has been reviewed but was not executed by an automated test. Test it in your own environment before relying on it.