2020-09-22 00:10:48 +02:00
|
|
|
#!/bin/bash
|
|
|
|
#### LOGGING
|
|
|
|
## from https://www.cubicrace.com/2016/03/log-tracing-mechnism-for-shell-scripts.html
|
|
|
|
[ -z "${SCRIPT_LOG+x}" ] && export SCRIPT_LOG=${HOME}/logs/scriptlog
|
|
|
|
mkdir -p "$(dirname ${SCRIPT_LOG})"
|
|
|
|
touch $SCRIPT_LOG
|
|
|
|
|
|
|
|
|
2022-09-14 14:43:45 +02:00
|
|
|
#for level in emerg alert crit err warning notice info debug; do
|
2020-09-22 00:10:48 +02:00
|
|
|
|
2022-09-14 14:43:45 +02:00
|
|
|
loglevels=(debug info notice warning err crit alert emerg)
|
2020-09-22 00:10:48 +02:00
|
|
|
|
2022-09-14 14:43:45 +02:00
|
|
|
for level in SCRIPTENTRY SCRIPTEXIT ENTRY EXIT; do
|
|
|
|
printf -v functext -- '%s() {
|
2020-09-22 09:08:16 +02:00
|
|
|
local loglevels
|
|
|
|
declare -a loglevels
|
2022-09-14 14:43:45 +02:00
|
|
|
loglevels=(emerg alert crit err warning notice info)
|
|
|
|
timeAndDate=$(date)
|
|
|
|
script_name="${BASH_SOURCE[0]##*/}"
|
|
|
|
local LOGLEVEL=${LOGLEVEL,,}
|
|
|
|
if [[ ! ${loglevels[@]} =~ "${LOGLEVEL:-${LOGLEVEL_DEFAULT,,}}" ]];then
|
|
|
|
echo "[%s] »${script_name}« ######################################################" >&2
|
2020-09-22 00:10:48 +02:00
|
|
|
fi
|
2022-08-11 12:11:01 +02:00
|
|
|
if [[ ! ${loglevels[*]} =~ "${FILELOGLEVEL:-$FILELOGLEVEL_DEFAULT}" ]];then
|
2022-09-14 14:43:45 +02:00
|
|
|
echo "[${timeAndDate}] [%s] ${script_name}" >> "${SCRIPT_LOG}"
|
|
|
|
fi }' "${level}" "${level^^}" "${level^^}"
|
|
|
|
eval "$functext"
|
|
|
|
export -f "${level}"
|
|
|
|
done
|
|
|
|
|
|
|
|
for level in trace debug info notice warning err crit alert emerg; do
|
|
|
|
loglevels=( ${loglevels[@]/$level} )
|
|
|
|
printf -v functext -- 'log%s() {
|
|
|
|
local msg="$@"
|
2021-12-03 09:00:40 +01:00
|
|
|
[ -z "${msg:+x}" ] && return 0
|
2020-09-22 00:10:48 +02:00
|
|
|
local loglevels
|
|
|
|
declare -a loglevels
|
2022-09-14 14:43:45 +02:00
|
|
|
loglevels=(%s)
|
|
|
|
timeAndDate=$(date)
|
|
|
|
script_name="${BASH_SOURCE[0]##*/}"
|
|
|
|
local LOGLEVEL=${LOGLEVEL,,}
|
|
|
|
if [[ ! ${loglevels[@]} =~ "${LOGLEVEL:-${LOGLEVEL_DEFAULT,,}}" ]];then
|
|
|
|
printf "[%%s] (%%s) %%s\n" %s "${FUNCNAME[1]}" "${msg}" >&2
|
2020-09-22 00:10:48 +02:00
|
|
|
fi
|
2022-08-11 12:11:01 +02:00
|
|
|
if [[ ! ${loglevels[*]} =~ "${FILELOGLEVEL:-$FILELOGLEVEL_DEFAULT}" ]];then
|
2022-09-14 14:43:45 +02:00
|
|
|
printf "[%%s] [%%s] (%%s) %%s\n" "$timeAndDate" %s "${FUNCNAME[1]}" "${msg}" >> "${SCRIPT_LOG}"
|
|
|
|
fi }' "$level" "$(echo ${loglevels[@]})" "${level^^}" "${level^^}"
|
|
|
|
eval "$functext"
|
|
|
|
export -f "log${level}"
|
|
|
|
done
|