Last active
April 27, 2020 11:29
-
-
Save peter-bloomfield/fa3c2da60cb1ec5d1630ac83ae01917d to your computer and use it in GitHub Desktop.
A bash function to echo coloured log messages.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#!/usr/bin/env bash | |
# Function echo text to the screen. | |
# There are two ways to invoke this: | |
# | |
# print LEVEL MESSAGE | |
# print MESSAGE | |
# | |
# In the first case, LEVEL can be one of: DEBUG, INFO, SUCCESS, WARNING, or ERROR. | |
# This determines the colour used to display the message. If the level is not recognised then it defaults to INFO. | |
# In the second case, the message is displayed as though LEVEL was set to INFO. | |
function print | |
{ | |
# If there are two arguments then the first is LEVEL and the second is MESSAGE. | |
# If there is only one argument then it is the message. LEVEL defaults to INFO. | |
local level="${1:-}" | |
local message="${2:-}" | |
if [[ "${message}" = "" ]]; then | |
message="${1:-}" | |
level="INFO" | |
fi | |
local format="\e[0m" | |
local resetFormat="\e[0m" | |
local prefix="" | |
# Pick a suitable display colour. | |
case "${level}" in | |
"DEBUG" ) | |
# Dim text | |
format="\e[2m" | |
prefix="[ DEBUG ]: " | |
;; | |
"INFO" ) | |
# Default text format. | |
prefix="[ INFO ]: " | |
;; | |
"SUCCESS" ) | |
# Green text. | |
format="\e[32m" | |
prefix="[SUCCESS]: " | |
;; | |
"WARNING" ) | |
# Yellow text. | |
format="\e[33m" | |
prefix="[WARNING]: " | |
;; | |
"ERROR" ) | |
# Bold/bright red text. | |
format="\e[1;31m" | |
prefix="[ ERROR ]: " | |
;; | |
* ) | |
# Use default format. | |
prefix="[${level}]: " | |
;; | |
esac | |
echo -e "${resetFormat}${format}${prefix}${message}${resetFormat}" | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Example usage: