Skip to content

Instantly share code, notes, and snippets.

@stephencroberts
Last active May 15, 2019 18:35
Show Gist options
  • Save stephencroberts/a8b372c48e836357b796cbd8c805b5af to your computer and use it in GitHub Desktop.
Save stephencroberts/a8b372c48e836357b796cbd8c805b5af to your computer and use it in GitHub Desktop.
Shell script function for logging with log levels and custom formatting (POSIX compatible)
##############################################################################
# Logs messages with a configurable logging level and format, accepting input
# from either stdin (such as a pipe) or as arguments
#
# Author: Stephen Roberts <stephenroberts@gmail.com>
#
# Globals:
# LOGLEVEL - arbitrary integer for desired log output level (default: 0)
#
# Arguments:
# --level [optional] - integer of log level for the message
# (default: 0)
# --format STRING [optional] - printf format string (default: "%b\n")
# ...message(s) [optional] - messages to log (read from stdin if no args)
#
# Examples:
# LOGLEVEL=3
# log --loglevel 3 --format "\e[33m%b\e[0m\n" "Hello, world!" # logged
# log --loglevel 4 "Debug message" # not logged
# echo "Error message" | log --loglevel 0 # logged
##############################################################################
log() {
loglevel=0
logfmt="%b\n"
LOGLEVEL=${LOGLEVEL:-0}
while [ $# -gt 0 ]; do
case $1 in
--level)
loglevel=$2
shift
shift
;;
--format)
logfmt=$2
shift
shift
;;
*)
logoutput="$1"
shift
;;
esac
done
if [ -z "$logoutput" ]; then
# Read from stdin
while read -r logoutput; do
if [ "$loglevel" -le "$LOGLEVEL" ]; then
# shellcheck disable=SC2059
printf "$logfmt" "$logoutput"
fi
done
else
# Log from args
if [ "$loglevel" -le "$LOGLEVEL" ]; then
# shellcheck disable=SC2059
printf "$logfmt" "$logoutput"
fi
fi
unset logoutput
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment