rwx/sh/log.sh

69 lines
1.2 KiB
Bash
Raw Normal View History

2024-11-18 11:07:42 +00:00
SH_LOG_LEVEL_FATAL=0
SH_LOG_LEVEL_ERROR=1
SH_LOG_LEVEL_WARN=2
SH_LOG_LEVEL_INFO=3
SH_LOG_LEVEL_DEBUG=4
SH_LOG_LEVEL_TRACE=5
2023-05-14 13:51:38 +00:00
2024-11-18 11:07:42 +00:00
SH_LOG_LEVEL=${SH_LOG_LEVEL_INFO}
2023-05-14 13:51:38 +00:00
2024-11-18 11:17:47 +00:00
sh_log() { sh_log_info "${@}"; }
2024-11-18 11:15:29 +00:00
sh_log_debug() {
2024-11-18 11:07:42 +00:00
if [ "${SH_LOG_LEVEL}" -ge "${SH_LOG_LEVEL_DEBUG}" ]; then
2024-11-19 11:21:29 +00:00
_sh_log "[DEBUG]" "${@}"
2024-11-12 06:20:25 +00:00
fi
}
2023-05-14 13:51:38 +00:00
2024-11-18 11:15:29 +00:00
sh_log_error() {
2024-11-19 08:58:15 +00:00
local code="${1}"
shift
[ -n "${code}" ] || sh_log_fatal 1 "No error code"
2024-11-18 11:07:42 +00:00
if [ "${SH_LOG_LEVEL}" -ge "${SH_LOG_LEVEL_ERROR}" ]; then
2024-11-19 11:21:29 +00:00
_sh_log "[ERROR]" "${@}" >&2
2024-11-19 08:58:15 +00:00
return "${code}"
2024-11-12 06:20:25 +00:00
fi
}
2023-05-14 13:51:38 +00:00
2024-11-18 11:15:29 +00:00
sh_log_fatal() {
2024-11-19 08:58:15 +00:00
local code="${1}"
shift
[ -n "${code}" ] || sh_log_fatal 1 "No error code"
2024-11-18 11:07:42 +00:00
if [ "${SH_LOG_LEVEL}" -ge "${SH_LOG_LEVEL_FATAL}" ]; then
2024-11-19 11:21:29 +00:00
_sh_log "[FATAL]" "${@}" >&2
2024-11-19 08:58:15 +00:00
exit "${code}"
2024-11-12 06:20:25 +00:00
fi
}
2023-05-14 13:51:38 +00:00
2024-11-18 11:15:29 +00:00
sh_log_info() {
2024-11-18 11:07:42 +00:00
if [ "${SH_LOG_LEVEL}" -ge "${SH_LOG_LEVEL_INFO}" ]; then
2024-11-19 11:21:29 +00:00
_sh_log "" "${@}"
2024-11-12 06:20:25 +00:00
fi
}
2023-05-14 13:51:38 +00:00
2024-11-18 11:15:29 +00:00
sh_log_trace() {
2024-11-18 11:07:42 +00:00
if [ "${SH_LOG_LEVEL}" -ge "${SH_LOG_LEVEL_TRACE}" ]; then
2024-11-19 11:21:29 +00:00
_sh_log "[TRACE]" "${@}"
2024-11-12 06:20:25 +00:00
fi
}
2023-05-14 13:51:38 +00:00
2024-11-18 11:15:29 +00:00
sh_log_warn() {
2024-11-18 11:07:42 +00:00
if [ "${SH_LOG_LEVEL}" -ge "${SH_LOG_LEVEL_WARN}" ]; then
2024-11-19 11:21:29 +00:00
_sh_log "[ WARN]" "${@}"
2024-11-12 06:20:25 +00:00
fi
}
2024-11-19 11:21:29 +00:00
_sh_log() {
local prefix="${1}"
shift
2024-11-25 17:30:35 +00:00
[ ${#} -gt 0 ] || set -- ""
2024-11-19 11:21:29 +00:00
local line
for line in "${@}"; do
2024-11-25 17:20:08 +00:00
if [ -n "${prefix}" ]; then
_sh_main_log "${prefix} ${line}"
else
_sh_main_log "${line}"
fi
2024-11-19 11:21:29 +00:00
done
2024-11-19 11:29:30 +00:00
}