summaryrefslogtreecommitdiffhomepage
path: root/subr.rtl/rtl_log.subr
blob: 3a7560a57910656f5e76a94f8b7c2c38ef7b25ce (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
79
80
81
82
83
84
85
86
87
88
#
# set +o errexit -o noglob -o nounset is assumed.
#

#
# Private globals and subroutines
#

RTLP_LOG_FNAME="";
RTLP_LOG_NO_ATTR=0;
RTLP_LOG_TAGS="";

rtlp_log_printf() {
	local _attr="${1}" _fmt_pfx="${2}" _fmt="${3#*;}" _fmt_argc="${3%%;*}"; shift 3;
	if [ "${#}" -ne "${_fmt_argc}" ]; then
		if [ "${_fmt_argc}" -eq 0 ]; then
			shift "${#}";
		else
			rtlp_log_printf "" "" "0;==> FIXME TODO XXX MESSAGE STRING ARGUMENT COUNT MISMATCH\n";
		fi;
	fi;
	_msg="$(printf "${_fmt_pfx}${_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; return 0;
};

#
# Public subroutines
#

rtl_log_clear_tags() {
	RTLP_LOG_TAGS=""; return 0;
};

rtl_log_enable_tags() {
	local IFS=","; set -- ${*};
	while [ "${#}" -gt 0 ]; do
		if ! rtl_lmatch "${RTLP_LOG_TAGS}" "${1}" ","; then
			RTLP_LOG_TAGS="${RTLP_LOG_TAGS:+${RTLP_LOG_TAGS},}${1}";
		fi; shift;
	done; return 0;
};

rtl_log_env_vars() {
	local _tag="${1}" _type="${2}" _arg_len_max=0; shift 2;

	rtl_log_msg "${_tag}" "${MSG_rtl_log_vars_header}" "${_type}";
	_arg_len_max="$(rtl_lmax "${@}")";
	while [ "${#}" -gt 0 ]; do
		rtl_log_msg "${_tag}"					\
			"2;%${_arg_len_max}.${_arg_len_max}s=%s"	\
			"${1%%=*}" "$(rtl_get_var_unsafe "${1#*=}")";
		shift;
	done; return 0;
};

rtl_log_msg() {
	local _tag="${1}" _fmt="${2}" _attr="" _exitfl=0; shift 2;

	[ "x${_tag}" = "xfatalexit" ] && { _tag="fatal"; _exitfl=1; };
	if rtl_lmatch "${RTLP_LOG_TAGS}" "${_tag}" ","; then
		eval _attr='${LOG_TAG_'"${_tag}"':-}';
		if [ "${#_attr}" -eq 0 ]; then
			rtlp_log_printf "" "" "0;==> FIXME TODO XXX UNKNOWN TAG \`${_tag}' PASSED TO rtl_log_msg()\n";
		fi;
		rtlp_log_printf "${_attr}" "==> $(rtl_date) " "${_fmt}" "${@}";
		if [ "${_exitfl}" -eq 1 ]; then
			exit 1;
		fi;
	fi; return 0;
};

rtl_log_set_fname() {
	RTLP_LOG_FNAME="${1}"; return 0;
};

rtl_log_set_no_attr() {
	RTLP_LOG_NO_ATTR="${1}"; return 0;
};

# vim:filetype=sh