Created
November 2, 2017 08:52
-
-
Save jemyzhang/de8fcb8e405dd470adf7488be4c93425 to your computer and use it in GitHub Desktop.
log print for shell
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
set_force_check() { | |
export force_check=1 | |
if [ x"$1" = x"0" ]; then | |
force_check=0 | |
fi | |
} | |
print_stack() { | |
local wholepath=$1 | |
# to avoid noise we start with 2 to skip get_stack caller | |
local i | |
local stack_size=${#FUNCNAME[@]} | |
echo -e "<--- Call Stack -->" >&2 | |
for (( i=2; i<$stack_size ; i++ )); do | |
local func="${FUNCNAME[$i]}" | |
[ x$func = x ] && func=MAIN | |
local linen="${BASH_LINENO[(( i - 1 ))]}" | |
local src="${BASH_SOURCE[$i]}" | |
[ x"$src" = x ] && src=non_file_source | |
if [ -n "$wholepath" ]; then | |
echo -e " $((i-1))> $func:" | |
echo -e " $src:$linen" >&2 | |
else | |
src=${src##*/} | |
echo -e " $((i-1))> $func: $src:$linen" >&2 | |
fi | |
done | |
} | |
log_err() { | |
local callidx=0 | |
echo -e "\033[31;1m[E]\033[0m $1" >&2 | |
print_stack | |
exit 1 | |
} | |
log_warn() { | |
echo -e "\033[33;1m[W]\033[0m $1" >&2 | |
if [ -n "$force_check" ]; then | |
if [ $force_check -eq 1 ]; then | |
print_stack | |
exit 1 | |
fi | |
fi | |
} | |
log_info() { | |
echo -e "\033[32;1m[I]\033[0m $1" >&2 | |
} | |
log_result() { | |
local msg="$1" | |
if [[ "$msg" =~ ^[0-9]+$ ]]; then | |
if [ $msg -eq 0 ]; then | |
printf "\033[32;1mOK\033[0m\n" | |
return 0 | |
else | |
printf "\033[31;1mFAILED\033[0m\n" | |
return 1 | |
fi | |
else | |
printf "\033[32;1m[I]\033[0m $msg ... " | |
fi | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment