Skip to content

Instantly share code, notes, and snippets.

@dtroyer
Created March 5, 2014 17:02
Show Gist options
  • Save dtroyer/9371456 to your computer and use it in GitHub Desktop.
Save dtroyer/9371456 to your computer and use it in GitHub Desktop.
DevStack-style log redirection wrapper
#!/bin/bash
# Test stack.sh logging scenarios
LOGFILE=${LOGFILE:-test.log}
SUMFILE=sum.log
VERBOSE=${VERBOSE:-True}
# Kill background processes on exit
trap exit_trap EXIT
function exit_trap {
local r=$?
jobs=$(jobs -p)
if [[ -n $jobs ]]; then
echo "exit_trap: cleaning up child processes"
kill 2>&1 $jobs
fi
exit $r
}
# Exit on any errors so that errors don't compound
trap err_trap ERR
function err_trap {
local r=$?
set +o xtrace
if [[ -n "$LOGFILE" ]]; then
echo "${0##*/} failed: full log in $LOGFILE"
else
echo "${0##*/} failed"
fi
exit $r
}
echo "Before"
ls -l /proc/self/fd
echo -e "\n\n"
sleep 1
# set up file handles like stack.sh
if [[ -n "$LOGFILE" ]]; then
# Copy stdout to fd 3
exec 3>&1
if [[ "$VERBOSE" == "True" ]]; then
# Redirect stdout/stderr to tee to write the log file
exec 1> >( awk -v logfile=${LOGFILE} '
/((set \+o$)|xtrace)/ { next }
{
cmd ="date +\"%Y-%m-%d %H:%M:%S.%3N | \""
cmd | getline now
close("date +\"%Y-%m-%d %H:%M:%S.%3N | \"")
sub(/^/, now)
print
print > logfile
fflush("")
}' ) 2>&1
# Set up a second fd for output
exec 6> >( tee "${SUMFILE}" )
else
# Set fd 1 and 2 to primary logfile
exec 1> "${LOGFILE}" 2>&1
# Set fd 6 to summary logfile and stdout
exec 6> >( tee "${SUMFILE}" >&3 )
fi
else
# Set up output redirection without log files
# Copy stdout to fd 3
exec 3>&1
if [[ "$VERBOSE" != "True" ]]; then
# Throw away stdout and stderr
exec 1>/dev/null 2>&1
fi
# Always send summary fd to original stdout
exec 6>&3
fi
# try stuff here
echo "During"
ls -l /proc/self/fd
echo -e "\n\n"
sleep 1
# tear down redirection
if [[ -n "$LOGFILE" ]]; then
exec 1>&3
# Force all output to stdout and logs now
exec 1> >( tee -a "${LOGFILE}" ) 2>&1
else
# Force all output to stdout now
exec 1>&3
fi
echo -e "\nAfter:"
ls -l /proc/self/fd
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment