Created
October 25, 2016 15:58
-
-
Save LukasRypl/be802fe58ba20a88b5ef460e4aeb3cbb to your computer and use it in GitHub Desktop.
Log and debug -- without XDEBUGFD so it works with bash version <4.1
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#!/bin/bash -eu | |
tag=$(dirname $(readlink -f $0))/$(basename $0) | |
# redirects output to logger, -s print it to stderr as well, -t add script name as a tag | |
# http://stackoverflow.com/questions/3173131/redirect-copy-of-stdout-to-log-file-from-within-bash-script-itself | |
exec > >( logger -s -t "${tag} [INFO ]" ) | |
# trap handler: print last error - filename, line, return code to stderr | |
function error-trap-handler() | |
{ | |
FILENAME=$(dirname $(readlink -f $0))/$(basename $0) | |
# filanem handled by output redirections as well but it does not work for included files | |
LASTLINE="$1" # argument 1: last line of error occurence | |
LASTERR="$2" # argument 2: error code of last command | |
echo "${FILENAME} at line ${LASTLINE}: exit status of the last command: ${LASTERR}" >&2 | |
} | |
# to print all commands with timestamps: export DEBUG=1 | |
if [ "$DEBUG" == "1" ] ; then | |
echo "DEBUG MODE is ON!" | |
set -x | |
echo "Traps: " | |
trap -p | |
echo "Flags: $-" | |
export PS4='+ $(date "+%F %T") ${BASH_SOURCE}:${LINENO} ${FUNCNAME[0]:+${FUNCNAME[0]}(): }' | |
exec 2> >( logger -s -p user.debug -t "${tag} [DEBUG]" ) | |
else | |
trap 'error-trap-handler ${LINENO} $?' ERR | |
# redirect std err | |
exec 2> >( logger -s -p user.err -t "${tag} [ERR ]" ) | |
fi |
Author
LukasRypl
commented
Nov 21, 2023
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment