Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
43 changes: 42 additions & 1 deletion log4bash.sh
Original file line number Diff line number Diff line change
Expand Up @@ -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")
Expand Down Expand Up @@ -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"
Expand All @@ -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;
}

Expand Down
38 changes: 38 additions & 0 deletions tests/bashful.sh
Original file line number Diff line number Diff line change
Expand Up @@ -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"