diff --git a/slog.sh b/slog.sh index 4bbf267..d06a339 100644 --- a/slog.sh +++ b/slog.sh @@ -6,10 +6,10 @@ # Licensed under the MIT license # http://github.com/swelljoe/slog #-------------------------------------------------------------------------------------------------- -set -e # Fail on first error # LOG_PATH - Define $LOG_PATH in your script to log to a file, otherwise # just writes to STDOUT. +LOG_PATH=${LOG_PATH:-""} # LOG_LEVEL_STDOUT - Define to determine above which level goes to STDOUT. # By default, all log levels will be written to STDOUT. @@ -26,10 +26,10 @@ SCRIPT_NAME="${SCRIPT_NAME#\./}" SCRIPT_NAME="${SCRIPT_NAME##/*/}" # Determines if we print colors or not -if [ $(tty -s) ]; then - readonly INTERACTIVE_MODE="off" -else +if [ -t 1 ] && [ -n "$TERM" ]; then readonly INTERACTIVE_MODE="on" +else + readonly INTERACTIVE_MODE="off" fi #-------------------------------------------------------------------------------------------------- @@ -61,20 +61,17 @@ prepare_log_for_nonterminal() { } log() { - local log_text="$1" - local log_level="$2" - local log_color="$3" + log_text="$1" + # Default level to "info" + log_level="${2:-INFO}" + log_color="${3:-${LOG_INFO_COLOR}}" # Levels for comparing against LOG_LEVEL_STDOUT and LOG_LEVEL_LOG - local LOG_LEVEL_DEBUG=0 - local LOG_LEVEL_INFO=1 - local LOG_LEVEL_SUCCESS=2 - local LOG_LEVEL_WARNING=3 - local LOG_LEVEL_ERROR=4 - - # Default level to "info" - [ -z ${log_level} ] && log_level="INFO"; - [ -z ${log_color} ] && log_color="${LOG_INFO_COLOR}"; + LOG_LEVEL_DEBUG=0 + LOG_LEVEL_INFO=1 + LOG_LEVEL_SUCCESS=2 + LOG_LEVEL_WARNING=3 + LOG_LEVEL_ERROR=4 # Validate LOG_LEVEL_STDOUT and LOG_LEVEL_LOG since they'll be eval-ed. case $LOG_LEVEL_STDOUT in diff --git a/tests/sloggi.sh b/tests/sloggi.sh old mode 100644 new mode 100755 index 796451c..1035773 --- a/tests/sloggi.sh +++ b/tests/sloggi.sh @@ -10,8 +10,13 @@ # XXX Output is not quite TAP, but should be. We could make a TAP mode for slog, or strip the # non-tap output in the log. -LOG_PATH="./my.log" -. ../slog.sh +set -euo pipefail + +SCRIPT_DIR="$(cd "$(dirname "$0")" && pwd)" +readonly SCRIPT_DIR + +LOG_PATH="$SCRIPT_DIR/my.log" +. "$SCRIPT_DIR/../slog.sh" log "ok 1 - This is regular log message... " @@ -27,7 +32,7 @@ log_error "ok 5 - Whoops! I made a booboo" LOG_LEVEL_LOG="ERROR" log_info "ok 6 - This should only appear on the console and not in the log file" -if [ -e ./my.log ]; then +if [ -e "$LOG_PATH" ]; then # Did the log get created with actual data? grep -q Whoops "$LOG_PATH" if [ $? -eq 0 ]; then @@ -53,3 +58,4 @@ log_debug "Uh oh. This should never show up in the log or the console." # Invalid log level...should default to info LOG_LEVEL_STDOUT="DOOTDOOT" log_info "ok 9 - This should show up, even though LOG_LEVEL_STDOUT set to $LOG_LEVEL_STDOUT." +