Created
August 17, 2022 08:06
-
-
Save OleksandrKucherenko/453fe8c44bd74e61fd69cd4b2fb44c38 to your computer and use it in GitHub Desktop.
BASH logger that listen to DEBUG environment variable
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
#!/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 "$@" |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
latest version in : https://github.com/OleksandrKucherenko/e-bash