Last active
June 3, 2022 23:00
-
-
Save WoozyMasta/293c785dd232fd6c2a06c1b2a89fccfd to your computer and use it in GitHub Desktop.
Bash logger
This file contains 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 | |
# Logging level | |
: "${LOG_LEVEL:=INFO}" | |
# Associative arrays for logging | |
declare -A log_c log_l | |
# Color codes | |
log_c[0]='\033[0m' # Reset colors | |
log_c[error]='\033[1;31m' # Red | |
log_c[warning]='\033[1;33m' # Yellow | |
log_c[info]='\033[1;34m' # Blue | |
log_c[success]='\033[1;32m' # Green | |
log_c[debug]='\033[1;37m' # Gray | |
log_c[none]='' # Nothing | |
# Logging priorities | |
log_l[silent]=0 # Higest prority, suppress all | |
log_l[error]=1 | |
log_l[warning]=2 | |
log_l[info]=3 | |
log_l[success]=3 | |
log_l[debug]=4 # Lowest prority, print all | |
# Print UTC date with format like: [05/17/21 20:05:21 UTC] | |
date-fmt() { date '+%D %T %Z' -u; } | |
log() { | |
local lvl="${1:-debug}" color="${1:-debug}" msg="${*:2}" accent=debug ident=7 | |
# Check log level argument is valid, or set to debug | |
[[ " ${!log_l[*]} " =~ \ "${lvl,,}"\ ]] || lvl=debug | |
# Check interactive tty | |
! [ -t 1 ] && color=none && accent=none && ident=1 | |
# Redirect all messages to the third stream | |
exec 3>&1 | |
# Redirect errors to stderr | |
[ "${lvl,,}" == error ] && exec 3>&2 | |
# If the log level is >= to the msg level then not suppress messages | |
[ "${log_l[${LOG_LEVEL,,}]}" -ge "${log_l[${lvl,,}]}" ] || exec 3>/dev/null | |
# Print log message | |
>&3 printf \ | |
"${log_c[${color,,}]}%-${ident}s${log_c[$accent]} [%s] ${log_c[0]}%s\n" \ | |
"${lvl^^}" "$(date-fmt)" "$msg" | |
# Exiting the script when an error or success message appears | |
[ "${lvl,,}" == error ] && exit 1 | |
[ "${lvl,,}" == success ] && exit 0 | |
} | |
# Test | |
LOG_LEVEL=debug | |
for l in foo debug info warning success error; do | |
log $l 'Voluptate sunt in dolor laboris ea amet eiusmod ad est quis labore.' | |
done |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment