Skip to content

Instantly share code, notes, and snippets.

@hcpadkins
Last active September 21, 2023 11:34
Show Gist options
  • Save hcpadkins/d45b370d39c5bb3eea72f87cc6ed3b1a to your computer and use it in GitHub Desktop.
Save hcpadkins/d45b370d39c5bb3eea72f87cc6ed3b1a to your computer and use it in GitHub Desktop.
Logging helpers
# Where is this script on the system.
SCRIPT_PATH="$(dirname "${BASH_SOURCE[0]}")"
SCRIPT_DIR="$(realpath "${SCRIPT_PATH}")"
SCRIPT_LOG="${SCRIPT_DIR}/../../test-harness.log"
# There are subtle differences between macOS and Linux that need to be accounted for.
PLATFORM="$(uname -o)"
# Colours for easier reading.
COLOUR_GREY="$(tput setaf 248)"
COLOUR_BLUE="$(tput setaf 68)"
COLOUR_GREEN="$(tput setaf 118)"
COLOUR_END="$(tput setaf 248)"
# Log writes the passed string to the log file and standard out with timestamps.
function log() {
_log_internal "${COLOUR_BLUE}${@}${COLOUR_END}"
}
# log_command executes the passed command, writing each log message from STDERR and
# STDOUT to the log file, with timestamps.
function log_command() {
eval "$@" 2>&1 | while IFS= read -r line; do
_log_internal " ${COLOUR_GREEN}${line}${COLOUR_END}"
done
return $?
}
# _log_internal handles formatting and writing of passed log messages. This should only
# be called by other functions, and not the user.
function _log_internal() {
date=$(date +"%Y-%m-%d %H:%M:%S" | tr -d '\n')
# Ensure the correct flags are used for sed on macOS.
SED="sed -e"
if [ ${PLATFORM} == "Darwin" ]; then
SED="sed -E"
fi
# The sed command is used here to strip any ANSI colour codes in the output but only
# when writing to file.
echo "${date} - ${@}" | tee >(${SED} $'s/\x1b\[[0-9;]*[mGKHF]//g' >> "${SCRIPT_LOG}")
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment