Skip to content

Instantly share code, notes, and snippets.

@unacceptable
Last active November 23, 2020 12:09
Show Gist options
  • Save unacceptable/ab32a3a7baeb593cda5f7ccf315582a0 to your computer and use it in GitHub Desktop.
Save unacceptable/ab32a3a7baeb593cda5f7ccf315582a0 to your computer and use it in GitHub Desktop.
#!/usr/bin/env bash
set -e
LOG_LEVEL='INFO'
NORMAL='\e[0m'
write_log(){
LOGGING="$1"
MESSAGE="$2"
TIMESTAMP="[$(date)]"
case "$LOG_LEVEL" in
DEBUG)
COLOR='\e[35m'
DEBUG=true
INFO=true
WARN=true
ERROR=true
;;
INFO)
COLOR='\e[36m'
DEBUG=false
INFO=true
WARN=true
ERROR=true
;;
WARN)
COLOR='\e[33m'
DEBUG=false
INFO=false
WARN=true
ERROR=true
;;
ERROR)
COLOR='\e[31m'
DEBUG=false
INFO=false
WARN=false
ERROR=true
;;
*)
echo "Invalid LOG_LEVEL - $LOG_LEVEL"
exit 2
;;
esac
case "$LOGGING" in
DEBUG)
"$DEBUG" || return 0
EXIT_CODE=0
;;
INFO)
"$INFO" || return 0
EXIT_CODE=0
;;
WARN)
"$WARN" || return 0
EXIT_CODE=0
;;
ERROR)
"$ERROR" || return 0
EXIT_CODE=2
;;
*)
echo "Invalid LOG_LEVEL - $LOGGING"
EXIT_CODE=3
;;
esac
echo -e "$TIMESTAMP - ${COLOR}${LOGGING}${NORMAL} - $MESSAGE"
if [ "$EXIT_CODE" != "0" ]; then
exit "$EXIT_CODE";
fi
}
# In your script just do:
########################################
# source write_log.sh
# LOG_LEVEL=DEBUG # Defaults to INFO if not specified.
#
# write_log "DEBUG" "This is some debugging message."
# write_log "INFO" "This is an info message."
# write_log "WARN" "This is a warning."
# write_log "ERROR" "Something terrible has happened."
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment