Skip to content

Instantly share code, notes, and snippets.

@pythoninthegrass
Last active October 2, 2024 22:23
Show Gist options
  • Save pythoninthegrass/e763dfc659e2501d5b3c1a2cd1278ded to your computer and use it in GitHub Desktop.
Save pythoninthegrass/e763dfc659e2501d5b3c1a2cd1278ded to your computer and use it in GitHub Desktop.
gum logging mvp
#!/usr/bin/env bash
# Function to log using gum
logger() {
local level msg OPTIND log_file log_dir log_path
level=""
msg=""
log_dir="/tmp"
log_file="gum.log"
log_path="${log_dir}/${log_file}"
while getopts ":l:" opt; do
case ${opt} in
l )
level=$OPTARG
;;
\? )
echo "Invalid option: $OPTARG" 1>&2
return 1
;;
: )
echo "Invalid option: $OPTARG requires an argument" 1>&2
return 1
;;
esac
done
shift $((OPTIND -1))
msg="$1"
gum_log() {
local cmd
cmd=(gum log --time rfc1123 --structured)
case "$level" in
"")
cmd+=("$msg")
;;
"debug" | "info" | "warn" | "error" | "fatal")
cmd+=("--level" "$level" "$msg")
;;
*)
cmd+=("--level" "error" "Invalid log level: $level")
;;
esac
# "${cmd[@]}" 2>&1
"${cmd[@]}" -o /dev/stdout
}
case "${LOG:-}" in
stdout)
gum_log
;;
log)
gum_log >> "$log_path"
;;
both)
gum_log | tee -a "$log_path"
;;
"")
gum_log
;;
*)
echo "Invalid LOG option: ${LOG}. Using 'none'." >&2
;;
esac
}
LOG=both
n=42
logger -l info "The secret to life is: $n"
@pythoninthegrass
Copy link
Author

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment