myshellconfig/logging
2022-09-14 15:03:44 +02:00

52 lines
1.8 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 emerg alert crit err warning notice info debug; do
for level in SCRIPTENTRY SCRIPTEXIT ENTRY EXIT; do
printf -v functext -- '%s() {
local loglevels
declare -a loglevels
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
fi
if [[ ! ${loglevels[*]} =~ "${FILELOGLEVEL:-$FILELOGLEVEL_DEFAULT}" ]];then
echo "[${timeAndDate}] [%s] ${script_name}" >> "${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
local loglevels
declare -a loglevels
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
fi
if [[ ! ${loglevels[*]} =~ "${FILELOGLEVEL:-$FILELOGLEVEL_DEFAULT}" ]];then
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
unset loglevels