Create a gist now

Instantly share code, notes, and snippets.

What would you like to do?
#!/bin/bash
#
# <script_name> <desc>
# Author: <author>
#
set -o errtrace
readonly LOG_DIR="/tmp/log"
readonly LOG_FILE="output.log"
assert() {
[ -d $LOG_DIR ] \
|| mkdir -p $LOG_DIR
}
configure_logger() {
local timeformat="+%Y%m%d_%H%M%S"
local log_endpoint="${LOG_DIR}/${LOG_FILE}"
coproc LOGGER {
while read -r line; do
echo "[$(date $timeformat)] $line" >> $log_endpoint
done
}
exec 3>&1
exec 4>&2
exec 1>&${LOGGER[1]}
exec 2>&1
}
restore_exec_redirect() {
exec 1>&3
exec 2>&4
}
logging() {
if [ $? -ne 0 ]; then
echo "failed on: $BASH_COMMAND"
restore_exec_redirect
echo "failed on: $BASH_COMMAND"
exit 1
else
echo "+ $BASH_COMMAND"
fi
}
helloworld() {
echo "hello world!"
}
sampletask() {
echo "first step"
echo "second step"
}
main() {
assert
configure_logger
trap "logging" DEBUG ERR
helloworld
sampletask
echo "end"
}
main
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment