summaryrefslogtreecommitdiffhomepage
path: root/subr/rtl_log.subr
blob: b91d13740529f3b7c6249cb2143cdb833f29396a (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
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