sh/sh/log.sh
2024-11-19 12:29:30 +01:00

64 lines
1.2 KiB
Bash

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
SH_LOG_LEVEL=${SH_LOG_LEVEL_INFO}
sh_log() { sh_log_info "${@}"; }
sh_log_debug() {
if [ "${SH_LOG_LEVEL}" -ge "${SH_LOG_LEVEL_DEBUG}" ]; then
_sh_log "[DEBUG]" "${@}"
fi
}
sh_log_error() {
local code="${1}"
shift
[ -n "${code}" ] || sh_log_fatal 1 "No error code"
if [ "${SH_LOG_LEVEL}" -ge "${SH_LOG_LEVEL_ERROR}" ]; then
_sh_log "[ERROR]" "${@}" >&2
return "${code}"
fi
}
sh_log_fatal() {
local code="${1}"
shift
[ -n "${code}" ] || sh_log_fatal 1 "No error code"
if [ "${SH_LOG_LEVEL}" -ge "${SH_LOG_LEVEL_FATAL}" ]; then
_sh_log "[FATAL]" "${@}" >&2
exit "${code}"
fi
}
sh_log_info() {
if [ "${SH_LOG_LEVEL}" -ge "${SH_LOG_LEVEL_INFO}" ]; then
_sh_log "" "${@}"
fi
}
sh_log_trace() {
if [ "${SH_LOG_LEVEL}" -ge "${SH_LOG_LEVEL_TRACE}" ]; then
_sh_log "[TRACE]" "${@}"
fi
}
sh_log_warn() {
if [ "${SH_LOG_LEVEL}" -ge "${SH_LOG_LEVEL_WARN}" ]; then
_sh_log "[ WARN]" "${@}"
fi
}
_sh_log() {
local prefix="${1}"
shift
local line
for line in "${@}"; do
[ -n "${prefix}" ] && printf "%s" "${prefix} "
echo "${line}"
done
}