Bash_Scripts/Templates/Functions/Logging/Logging.bash
2021-08-04 21:17:20 -05:00

67 lines
1.7 KiB
Bash
Executable File

#!/bin/bash --posix
set -e
log() {
# Print a message and send it to stdout or stderr depending upon log level, also configurable with debug etc.
#
# Arguments:
# level <type: string> <position: 1> <required: true>
# - The log level, defined within a case check in this function
# message <type: string> <position: 2> <required: true>
# - The info message
# line_number <type: int> <position: 3> <required: false>
# - The line number of the calling function (${LINNO})
#
# Usage:
# log "info" "Could not find that directory"
#
# POSIX Compliant:
# Yes
#
# Set debug status depending if a global debug variable has been set to either 1 or 0
local debug
if [ ${DEBUG} ]; then
debug=${DEBUG}
else
debug=0
fi
local FORMAT
FORMAT="[$(date +%Y-%m-%dT%H:%M:%S%z)]"
# Convert the level to uppercase
local level
level=$(echo "${1}" | tr '[:lower:]' '[:upper:]')
local message
message="${2}"
case "${level}" in
INFO)
# Output all info log levels to stdout
printf "${FORMAT}[INFO] %s\n" "${message}" >&1
return 0
;;
DEBUG)
[[ ${debug} == 0 ]] && return 0
printf "${FORMAT}[DEBUG] %s\n" "${message}" >&1
return 0
;;
ERROR)
# Output all error log levels to stderr
printf "${FORMAT}[ERROR] %s\n" "${message}" >&2
return 0
;;
# Further log levels can be added by extending this switch statement with more comparisons
*) # Default case, no matches
# Returns non-zero code as an improper log option was passed, this helps with using `set -e`
log "ERROR" "Invalid log level passed, received level \"${level}\" with message \"${message}\""
return 1
esac
}