Last active
November 23, 2020 12:09
-
-
Save unacceptable/ab32a3a7baeb593cda5f7ccf315582a0 to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#!/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