diff options
Diffstat (limited to 'subr.rtl/rtl_log.subr')
-rw-r--r-- | subr.rtl/rtl_log.subr | 78 |
1 files changed, 78 insertions, 0 deletions
diff --git a/subr.rtl/rtl_log.subr b/subr.rtl/rtl_log.subr new file mode 100644 index 00000000..b91d1374 --- /dev/null +++ b/subr.rtl/rtl_log.subr @@ -0,0 +1,78 @@ +# +# set +o errexit -o noglob -o nounset is assumed. +# + +# +# Private globals and subroutines +# +RTLP_LOG_NO_ATTR=0; +RTLP_LOG_FNAME=""; +RTLP_LOG_LVL="0"; +rtl_log_set_fname() { RTLP_LOG_FNAME="${1}"; }; +rtl_log_set_lvl() { RTLP_LOG_LVL="${1}"; }; +rtl_log_set_no_attr() { RTLP_LOG_NO_ATTR="${1}"; }; + +rtlp_log_printf() { + local _attr="${1}" _fmt="${2}"; shift 2; _msg="$(printf "${_fmt}" "${@}")"; + if [ -n "${RTLP_LOG_FNAME}" ]; then + printf "%s\n" "${_msg}" >> "${RTLP_LOG_FNAME}"; + fi; + if [ "${RTLP_LOG_NO_ATTR:-0}" -eq 0 ]; then + printf "\033[0m\033[${_attr}m%s\033[0m\n" "${_msg}"; + else + printf "%s\n" "${_msg}"; + fi; +}; + +# +# Public globals +# +RTL_LOG_MSG_FATAL_COLOUR=91; # Bright red +RTL_LOG_MSG_WARNING_COLOUR=31; # Dark red +RTL_LOG_MSG_SUCCESS_COLOUR=33; # Dark yellow +RTL_LOG_MSG_SUCCESS_END_COLOUR=32; # Dark green +RTL_LOG_MSG_INFO_COLOUR=93; # Bright yellow +RTL_LOG_MSG_INFO_END_COLOUR=92; # Bright green +RTL_LOG_MSG_NOTICE_COLOUR=96; # Bright cyan +RTL_LOG_MSG_VERBOSE_COLOUR=90; # Dark grey +RTL_LOG_MSG_DEBUG_COLOUR=36; # Dark cyan + + +rtl_log_env_vars() { + local _arg_len_max=0; + rtl_log_msg info "Variables for this ${1:-build}:"; shift; + _arg_len_max="$(rtl_lmax "${@}")"; + while [ "${#}" -gt 0 ]; do + rtl_log_msg info \ + "%${_arg_len_max}.${_arg_len_max}s=%s" \ + "${1%%=*}" "$(rtl_get_var_unsafe "${1#*=}")"; + shift; + done; +}; + +rtl_log_msg() { + local _lvl="${1}" _fmt="${2}" _attr=""; shift 2; + case "${RTLP_LOG_LVL:-0}" in + 0) rtl_lmatch "notice verbose debug" "${_lvl}" && return; ;; + 1) rtl_lmatch "verbose debug" "${_lvl}" && return; ;; + 2) rtl_lmatch "debug" "${_lvl}" && return; ;; + 3) ;; + esac; + case "${_lvl}" in + fatal|fatalexit) _attr="${RTL_LOG_MSG_FATAL_COLOUR}"; ;; + warning) _attr="${RTL_LOG_MSG_WARNING_COLOUR}"; ;; + success) _attr="${RTL_LOG_MSG_SUCCESS_COLOUR}"; ;; + success_end) _attr="${RTL_LOG_MSG_SUCCESS_END_COLOUR}"; ;; + info) _attr="${RTL_LOG_MSG_INFO_COLOUR}"; ;; + info_end) _attr="${RTL_LOG_MSG_INFO_END_COLOUR}"; ;; + notice) _attr="${RTL_LOG_MSG_NOTICE_COLOUR}"; ;; + verbose) _attr="${RTL_LOG_MSG_VERBOSE_COLOUR}"; ;; + debug) _attr="${RTL_LOG_MSG_DEBUG_COLOUR}"; ;; + esac; + rtlp_log_printf "${_attr}" "==> %s ${_fmt}" "$(rtl_date)" "${@}"; + if [ "x${_lvl}" = "xfatalexit" ]; then + exit 1; + fi; +}; + +# vim:filetype=sh |