diff --git a/README.md b/README.md index b77ec26..7c56f2f 100644 --- a/README.md +++ b/README.md @@ -44,6 +44,9 @@ You can control the logging level while calling a script by setting the `LOGGER_ You can set `LOGGER_LVL=none` to disable all logging. +## Color +By default, log output is colorized by level. This behavior can be disabled by setting `LOGGER_COLOR=0` + ## Timestamp customisation Underneath, the `date` command is used to display the timestamp. Simply set the `LOGGER_FMT` to any valid format supported by `date`. diff --git a/tinylogger.bash b/tinylogger.bash index ae36cc8..f31e618 100644 --- a/tinylogger.bash +++ b/tinylogger.bash @@ -24,15 +24,32 @@ # Author: Nagarjuna Kumarappan # defaults -LOGGER_FMT=${LOGGER_FMT:="%Y-%m-%d %H:%M:%S"} LOGGER_LVL=${LOGGER_LVL:="info"} +LOGGER_FMT=${LOGGER_FMT:="%Y-%m-%d %H:%M:%S"} +LOGGER_COLOR=${LOGGER_COLOR:="1"} + +_tlog_levels=(error warn info debug) +_tlog_colors=('\033[0;31m' '\033[0;33m' '\033[0;32m' '\033[0;36m') + +function _tlog_head { + idx=$1 + nc='\033[0m' + lvlname=${_tlog_levels[$idx]^^} + + if (("$LOGGER_COLOR")); then + printf "$(date "+${LOGGER_FMT}") - ${_tlog_colors[$idx]}${lvlname}${nc}" + else + printf "$(date "+${LOGGER_FMT}") - ${lvlname}" + fi +} function tlog { - action=$1 && shift - case $action in - debug) [[ $LOGGER_LVL =~ debug ]] && echo "$( date "+${LOGGER_FMT}" ) - DEBUG - $@" 1>&2 ;; - info) [[ $LOGGER_LVL =~ debug|info ]] && echo "$( date "+${LOGGER_FMT}" ) - INFO - $@" 1>&2 ;; - warn) [[ $LOGGER_LVL =~ debug|info|warn ]] && echo "$( date "+${LOGGER_FMT}" ) - WARN - $@" 1>&2 ;; - error) [[ ! $LOGGER_LVL =~ none ]] && echo "$( date "+${LOGGER_FMT}" ) - ERROR - $@" 1>&2 ;; - esac - true; } + action=$1 && shift + case $action in + debug) [[ $LOGGER_LVL =~ debug ]] && echo "$(_tlog_head 3) - $@" 1>&2 ;; + info) [[ $LOGGER_LVL =~ debug|info ]] && echo "$(_tlog_head 2) - $@" 1>&2 ;; + warn) [[ $LOGGER_LVL =~ debug|info|warn ]] && echo "$(_tlog_head 1) - $@" 1>&2 ;; + error) [[ ! $LOGGER_LVL =~ none ]] && echo "$(_tlog_head 0) - $@" 1>&2 ;; + esac + true; +}