98 lines
2.3 KiB
Bash
98 lines
2.3 KiB
Bash
#!/bin/bash
|
|
# Ver: 1.2 by Endial Fang (endial@126.com)
|
|
#
|
|
# 日志输出函数库
|
|
|
|
#[[ ${ENV_DEBUG:-false} = true ]] && set -x
|
|
MODULE="$(basename "$0")"
|
|
|
|
# 定义颜色代码函数
|
|
get_color_code() {
|
|
local color="$1"
|
|
case "$color" in
|
|
"reset") echo '\033[0m' ;;
|
|
"red") echo '\033[38;5;1m' ;;
|
|
"green") echo '\033[38;5;2m' ;;
|
|
"yellow") echo '\033[38;5;3m' ;;
|
|
"blue") echo '\033[38;5;4m' ;;
|
|
"magenta") echo '\033[38;5;5m' ;;
|
|
"cyan") echo '\033[38;5;6m' ;;
|
|
*) echo "" ;;
|
|
esac
|
|
}
|
|
|
|
# 打印输出到 STDERR 设备
|
|
stderr_print() {
|
|
printf "%b\\n" "${*}" >&2
|
|
}
|
|
|
|
# 判断是否处于调试模式
|
|
is_debug_mode() {
|
|
local debug_var="${ENV_DEBUG:-false}"
|
|
shopt -s nocasematch
|
|
[[ "$debug_var" = 1 || "$debug_var" =~ ^(yes|true)$ ]]
|
|
}
|
|
|
|
# 输出实际日志信息
|
|
# 参数:
|
|
# $1 - 日志信息
|
|
log() {
|
|
local debug_info
|
|
if is_debug_mode; then
|
|
debug_info="$(get_color_code "cyan")${APP_NAME:-}:${MODULE:-}"
|
|
else
|
|
debug_info="$(get_color_code "cyan")${APP_NAME:-}"
|
|
fi
|
|
local timestamp="$(get_color_code "magenta")$(date "+%F %T.%3N")$(get_color_code "reset")"
|
|
stderr_print "$debug_info $timestamp $*"
|
|
}
|
|
|
|
# 输出调试类日志信息,尽量少使用
|
|
# 参数:
|
|
# $1 - 日志信息
|
|
debug() {
|
|
if is_debug_mode; then
|
|
log "$(get_color_code "blue")DBG$(get_color_code "reset"): $*"
|
|
fi
|
|
}
|
|
|
|
# 输出提示信息类日志信息
|
|
# 参数:
|
|
# $1 - 日志信息
|
|
info() {
|
|
log "$(get_color_code "green")INF$(get_color_code "reset"): $*"
|
|
}
|
|
|
|
# 输出警告类日志信息至sterr
|
|
# 参数:
|
|
# $1 - 日志信息
|
|
warn() {
|
|
log "$(get_color_code "yellow")WRN$(get_color_code "reset"): $*"
|
|
}
|
|
|
|
# 输出错误类日志信息至sterr,并退出脚本
|
|
# 参数:
|
|
# $1 - 日志信息
|
|
error() {
|
|
log "$(get_color_code "red")ERR$(get_color_code "reset"): $*"
|
|
}
|
|
|
|
# 缩进一个字符串
|
|
# 参数:
|
|
# $1 - 待缩进的字符串 (默认为空字符串)
|
|
# $2 - 缩进的字符数 (默认: 4)
|
|
# $3 - 缩进使用的字符 (默认: " ")
|
|
indent() {
|
|
local string="${1:-}"
|
|
local num="${2:?missing num}"
|
|
local char="${3:-" "}"
|
|
|
|
# 生成缩进填充的字符串
|
|
local indent_unit=""
|
|
for ((i = 0; i < num; i++)); do
|
|
indent_unit="${indent_unit}${char}"
|
|
done
|
|
|
|
echo "$string" | sed "s/^/${indent_unit}/"
|
|
}
|