Skip to content

Instantly share code, notes, and snippets.

@OleksandrKucherenko
Created August 17, 2022 08:06
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save OleksandrKucherenko/453fe8c44bd74e61fd69cd4b2fb44c38 to your computer and use it in GitHub Desktop.
Save OleksandrKucherenko/453fe8c44bd74e61fd69cd4b2fb44c38 to your computer and use it in GitHub Desktop.
BASH logger that listen to DEBUG environment variable
#!/usr/bin/env bash
# shellcheck disable=SC2155,SC2034,SC2059
# get script directory
SCRIPT_DIR="$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)"
#
# Register debug logger functions that are controlled by DEBUG= environment variable
# Examples:
# DEBUG=* - print all logs
# DEBUG=*,-dependencies - print all logs except 'dependencies'
# DEBUG=common,token - print logs for 'common' and 'token'
#
function logger() {
#
# Usage:
# source "$SCRIPT_DIR/logger.sh" && logger tag "$@"
# echoTag "print only if DEBUG=tag is set"
# printfTag "print only if DEBUG=tag is set %s" "something"
#
local tag=${1}
local Suffix=${1^}
# keep it disabled by default
declare -g -A TAGS && TAGS+=([$tag]=0)
# declare logger functions
eval "$(
cat <<EOF
#
# begin
#
function echo${Suffix}() {
[[ "\${TAGS[$tag]}" == "1" ]] && builtin echo "\$@"
}
function printf${Suffix}() {
[[ "\${TAGS[$tag]}" == "1" ]] && builtin printf "\$@"
}
function configDebug${Suffix}() {
local args=("\$@")
IFS="," read -r -a tags <<<\$(echo "\$DEBUG")
[[ "\${args[*]}" =~ "--debug" ]] && TAGS+=([$tag]=1)
[[ "\${tags[*]}" =~ "$tag" ]] && TAGS+=([$tag]=1)
[[ "\${tags[*]}" =~ "*" ]] && TAGS+=([$tag]=1)
[[ "\${tags[*]}" =~ "-$tag" ]] && TAGS+=([$tag]=0)
# builtin echo "done! \${!TAGS[@]} \${TAGS[@]}"
}
#
# end
#
EOF
)"
# configure logger
eval "configDebug${Suffix}" "$@"
# dump created loggers
[[ "$tag" != "common" ]] && eval "echoCommon \"${cl_grey}Logger tags :\" \"\${!TAGS[@]}\" \"|\" \"\${TAGS[@]}\" \"${cl_reset}\"" 2>/dev/null
}
# register own logger
logger common "$@"
@OleksandrKucherenko
Copy link
Author

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment