Skip to content

Instantly share code, notes, and snippets.

@bekcpear
Last active May 6, 2022 08:19
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save bekcpear/1d8a6deeca485649a42120d961cd8d1b to your computer and use it in GitHub Desktop.
Save bekcpear/1d8a6deeca485649a42120d961cd8d1b to your computer and use it in GitHub Desktop.
#!/bin/bash
#
# @VARIABLE: LOGLEVEL
# #DEFAULT: 2
# @INTERNAL
# @DESCRIPTION:
# Used to control output level of messages. Should only be setted
# by shell itself.
# 0 -> DEBUG; 1 -> INFO; 2 -> NORMAL; 3 -> WARNNING; 4 -> ERROR
LOGLEVEL=2
# @FUNCTION: _log
# @USAGE: <[dinwe]> <message>
# @INTERNAL
# @DESCRIPTION:
# Echo messages with a unified format.
# 'd' means showing in DEBUG level;
# 'i' means showing in INFO level;
# 'n' means showing in NORMAL level;
# 'w' means showing in WARNNING level;
# 'e' means showing in ERROR level;
# Msg will be printed to the standard output normally
# when this function is called without any option.
function _log() {
local color='\033[0m'
local reset='\033[0m'
local ofd='&1'
local -i lv=2
if [[ ! ${1} =~ ^[dinwe]+$ ]]; then
echo "UNRECOGNIZED OPTIONS OF INTERNAL <_log> FUNCTION!" >&2
exit 1
fi
case ${1} in
*e*)
lv=4
color='\033[31m'
ofd='&2'
;;
*w*)
lv=3
color='\033[33m'
ofd='&2'
;;
*n*)
lv=2
color='\033[36m'
;;
*i*)
lv=1
;;
*d*)
lv=0
;;
esac
if [[ ${lv} -ge ${LOGLEVEL} ]]; then
shift
local prefix=""
local msg="${@}"
if [[ ${lv} != 2 ]]; then
prefix="[$(date '+%Y-%m-%d %H:%M:%S')] "
fi
eval ">${ofd} echo -e '${color}${prefix}${msg//\'/\'\\\'\'}${reset}'"
fi
}
# @FUNCTION: _fatal
# @USAGE: <exit-code> <message>
# @INTERNAL
# @DESCRIPTION:
# Print an error message and exit shell.
function _fatal() {
if [[ ${1} =~ ^[[:digit:]]+$ ]]; then
local exit_code=${1}
shift
else
local exit_code=1
fi
_log e "${@}"
exit ${exit_code}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment