diff --git a/log4bash.sh b/log4bash.sh index 8c17690..bb1d9d3 100755 --- a/log4bash.sh +++ b/log4bash.sh @@ -14,6 +14,18 @@ SCRIPT_NAME="${SCRIPT_NAME#\./}" SCRIPT_NAME="${SCRIPT_NAME##/*/}" SCRIPT_BASE_DIR="$(cd "$( dirname "$0")" && pwd )" +# +# Configuration settings +# + +# The default time format string +log4bash_timefmt="+%Y-%m-%d %H:%M:%S %Z" + +# The default list of log handler functions +log4bash_handlers=("log_echo") + +context=() + # This should probably be the right way - didn't have time to experiment though # declare -r INTERACTIVE_MODE="$([ tty --silent ] && echo on || echo off)" declare -r INTERACTIVE_MODE=$([ "$(uname)" == "Darwin" ] && echo "on" || echo "off") @@ -61,6 +73,28 @@ prepare_log_for_nonterminal() { sed "s/[[:cntrl:]]\[[0-9;]*m//g" } +context_push() { + while [ "$1" ]; do + context+=($1); shift + done +} + +context_pop() { + unset context[${#context[@]}-1] +} + +join_by() { + local IFS="$1"; shift + echo "$*" +} + +# +# Handlers +# +log_echo() { + echo -e "$*" +} + log() { local log_text="$1" local log_level="$2" @@ -70,7 +104,14 @@ log() { [[ -z ${log_level} ]] && log_level="INFO"; [[ -z ${log_color} ]] && log_color="${LOG_INFO_COLOR}"; - echo -e "${log_color}[$(date +"%Y-%m-%d %H:%M:%S %Z")] [${log_level}] ${log_text} ${LOG_DEFAULT_COLOR}"; + # First build the log message + msg="${log_color}$(join_by ' ' [$(date "${log4bash_timefmt}")] [${log_level}] ${context[@]} ${log_text})${LOG_DEFAULT_COLOR}"; + + # And then dispatch it to handlers + for handler in ${log4bash_handlers[@]}; do + eval $handler \"$msg\" + done + return 0; } diff --git a/tests/bashful.sh b/tests/bashful.sh index c9b8662..0a6cdb3 100755 --- a/tests/bashful.sh +++ b/tests/bashful.sh @@ -22,3 +22,41 @@ log_captains "What was in the captain's toilet?"; # If you have the "say" command (e.g. on a Mac) log_speak "Resistance is futile"; + +# +# Now for an example how we can change the timestamp format +# +log4bash_timefmt="+%Y-%m-%dT%H:%M:%S%z"; + +log_info "ISO-8601 master race! Exterminate!"; + +# +# How to use a context stack +# +log_info "Starting blobalizer"; + +context_push "blobalizer_started"; + +log_warning "We are beginning task"; + +context_push "task1"; + +log_success "Task has ended"; + +context_pop; + +log_info "Taking another task from queue"; + +# +# Now to add some new handlers +# + +log_syslog() { + logger "$*" +} + +# Add the handler at the end of the chain +log4bash_handlers+=("log_syslog") + +log_info "This message will also be logged to syslog, check it now" +