Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Add level-based color output #3

Open
wants to merge 3 commits into
base: master
Choose a base branch
from
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
3 changes: 3 additions & 0 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -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`.
Expand Down
35 changes: 26 additions & 9 deletions tinylogger.bash
Original file line number Diff line number Diff line change
Expand Up @@ -24,15 +24,32 @@
# Author: Nagarjuna Kumarappan <[email protected]>

# 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;
}