Skip to content

Instantly share code, notes, and snippets.

@mike-callahan
Created September 3, 2025 04:02
Show Gist options
  • Save mike-callahan/eba88bafa9cc5b9e955c30ef00537661 to your computer and use it in GitHub Desktop.
Save mike-callahan/eba88bafa9cc5b9e955c30ef00537661 to your computer and use it in GitHub Desktop.
Simple bash logger
# -------------------------------------------------------------------
# log: simple logger with timestamp, log levels, and color support
#
# Usage:
# log "message"
# log INFO "message"
# log WARN "message with \nnewlines"
# log ERROR "something went wrong"
# log DEBUG "debug info"
#
# Pipe command output:
# some_command |& log
# some_command |& log WARN
#
# Notes:
# - Timestamps are bold.
# - Log levels: INFO (green), WARN (yellow), ERROR (red), DEBUG (cyan).
# - Colors auto-disable if stdout isn't a TTY or if $NO_COLOR is set.
# - With pipes: prints one timestamp+level header, then passes through output.
# -------------------------------------------------------------------
log() {
# level is optional first arg: INFO|WARN|ERROR|DEBUG
local level="INFO"
case "$1" in INFO|WARN|ERROR|DEBUG) level="$1"; shift;; esac
# bold timestamp
local ts="\e[1m$(date '+%Y-%m-%d %H:%M:%S')\e[0m"
# color (only if stdout is a terminal and NO_COLOR isn't set)
local cs="" ce=""
if [ -t 1 ] && [ -z "${NO_COLOR:-}" ]; then
case "$level" in
INFO) cs="\e[32m" ;; # green
WARN) cs="\e[33m" ;; # yellow
ERROR) cs="\e[31m" ;; # red
DEBUG) cs="\e[36m" ;; # cyan
esac
ce="\e[0m"
fi
if [ $# -gt 0 ]; then
# args path: interpret escapes like \n
printf "[%b] [%b%b%b] %b\n" "$ts" "$cs" "$level" "$ce" "$*"
else
# pipe path: print header once, then pass stdin through
printf "[%b] [%b%b%b] " "$ts" "$cs" "$level" "$ce"
cat
fi
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment