myshellconfig/logging
2022-09-14 16:38:04 +02:00

41 lines
1.7 KiB
Bash

#!/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
for level in SCRIPTENTRY SCRIPTEXIT ENTRY EXIT; do
printf -v functext -- '%s() {
local loglevels=(emerg alert crit err warning notice info)
timeAndDate=$(date)
local LOGLEVEL=${LOGLEVEL,,}
if [[ ! ${loglevels[@]} =~ "${LOGLEVEL:-${LOGLEVEL_DEFAULT,,}}" ]];then
echo "[%s] »${BASH_SOURCE[0]##*/} (${FUNCNAME[1]}) « ######################################################" >&2
fi
if [[ ! ${loglevels[*]} =~ "${FILELOGLEVEL:-$FILELOGLEVEL_DEFAULT}" ]];then
echo "[${timeAndDate}] [%s] $(basename -- $0) (${FUNCNAME[1]})" >> "${SCRIPT_LOG}"
fi }' "${level}" "${level^^}" "${level^^}"
eval "$functext"
export -f "${level}"
done
loglevels=(trace debug info notice warning err crit alert emerg)
for level in ${loglevels[@]}; do
loglevels=( ${loglevels[@]/$level} )
printf -v functext -- 'log%s() {
local msg="$@"
[ -z "${msg:+x}" ] && return 0
loglevels=(%s)
timeAndDate=$(date)
local LOGLEVEL=${LOGLEVEL,,}
if [[ ! ${loglevels[@]} =~ "${LOGLEVEL:-${LOGLEVEL_DEFAULT,,}}" ]];then
printf "[%%s] (%%s) %%s\n" %s "${FUNCNAME[1]}" "${msg}" >&2
fi
if [[ ! ${loglevels[*]} =~ "${FILELOGLEVEL:-$FILELOGLEVEL_DEFAULT}" ]];then
printf "[%%s] [%%s] %%s (%%s) %%s\n" "$timeAndDate" %s "$(basename -- $0)" "${FUNCNAME[1]}" "${msg}" >> "${SCRIPT_LOG}"
fi }' "$level" "$(echo ${loglevels[@]})" "${level^^}" "${level^^}"
eval "$functext"
export -f "log${level}"
done
unset loglevels