Last active
May 15, 2019 18:35
-
-
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)
This file contains hidden or 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
############################################################################## | |
# Logs messages with a configurable logging level and format, accepting input | |
# from either stdin (such as a pipe) or as arguments | |
# | |
# Author: Stephen Roberts <[email protected]> | |
# | |
# 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