Skip to content

Instantly share code, notes, and snippets.

@dnut
Last active April 6, 2022 02:48
Show Gist options
  • Save dnut/03e57d693d816e256cf15aa74ccf1224 to your computer and use it in GitHub Desktop.
Save dnut/03e57d693d816e256cf15aa74ccf1224 to your computer and use it in GitHub Desktop.
Logging library for bash to configure the current script to log to console and a file with timestamp and log level
# Reads from stdin and prefixes each line with a timestamp (if true) and default log level (if missing)
prefix_log() { local default_level=$1
while read -r line; do
local timestamp=''
local level=''
if ! [[ $line =~ ^[0-9]{4}-[0-9]{2}-[0-9]{2} ]]; then
timestamp="$(date +"%Y-%m-%d %T.%3N") - "
if ! [[ $line =~ ^(TRACE|DEBUG|INFO|WARN|ERROR) ]]; then
level="$default_level - "
fi
fi
echo "$timestamp$level$line"
done
}
# Sets up script to prefix every line with timestamp and log level and send stdout and stderr to a file
# - use_xtrace: If 'true', log every line of code as it is executed
# - stderr_to_stdout: If 'true', redirect stderr to stdout
configure_logging() { local path=$1; local stderr_to_stdout=$2; local use_xtrace=$3
mkdir -p "$(basename "$path")"
exec 3>> "$path"
exec > >(prefix_log INFO | tee -i >(cat >&3))
if [[ $stderr_to_stdout == true ]]; then
exec 2> >(prefix_log ERROR)
else
exec 2> >(prefix_log ERROR | tee -i >(cat >&3) >&2)
fi
PS4=' TRACE - $(basename $BASH_SOURCE):$LINENO.$BASH_SUBSHELL${FUNCNAME[0]:+ [${FUNCNAME[0]}]} + '
if [[ $use_xtrace == true ]]; then
set -x
fi
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment