Skip to content

Instantly share code, notes, and snippets.

@gkze
Last active August 29, 2015 14:11
Show Gist options
  • Save gkze/caf076cf381997e39061 to your computer and use it in GitHub Desktop.
Save gkze/caf076cf381997e39061 to your computer and use it in GitHub Desktop.
Colored logging in bash
#!/bin/bash
# Exit on error
set -e
# Logging utility
log() {
# Escape codes for colored output
C_GREEN="\033[32m"
C_NORMAL="\033[0m"
C_RED="\033[31m"
C_YELLOW="\033[33m"
level=$1
# set the exit flag if logging error
if [ "$level" = "error" ]; then
should_exit=true
err_flag="1>&2"
else
should_exit=false
fi
if [ "$DOTS_QUIET" = "true" ] && [ "$level" != "error" ]; then
return 0
fi
case $level in
debug)
color=$C_NORMAL
;;
error)
color=$C_RED
;;
info)
color=$C_GREEN
;;
warn)
color=$C_YELLOW
;;
esac
# On to the next argument
shift
# Output
echo -e "${color}[$(date +'%Y-%m-%d %H:%M:%S')] $(echo "$level" | tr '[:lower:]' '[:upper:]'):\t${*}$C_NORMAL" "$err_flag"
if [ "$should_exit" == "true" ]; then
exit 1
fi
return 0
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment