Skip to content

Instantly share code, notes, and snippets.

@coffeejoshua
Created May 4, 2023 19:17
Show Gist options
  • Save coffeejoshua/f5b7fa014086a52a7f73724f6844ac07 to your computer and use it in GitHub Desktop.
Save coffeejoshua/f5b7fa014086a52a7f73724f6844ac07 to your computer and use it in GitHub Desktop.
Bash Logging Snip
#!/bin/bash
# bash_logger.sh
LOGFILE=log_output.txt
#######################################
# Log to the terminal and a file.
# Globals:
# LOGFILE
# Arguments:
# [level] [msg]
# Usage:
# log "NOTICE some notice level message"
# log "INFO some info message"
# log "WARNING some warning message"
# log "ERROR some error message"
# log "DEBUG (catch-all) some debug message"
#######################################
function log(){
DEFAULT="\033[0m"
log_notice() {
GREEN_COLOR="\033[0;32m"
echo -e "${GREEN_COLOR}${1:-} ${DEFAULT}"
}
log_info() {
BLUE_COLOR="\033[0;34m"
echo -e "${BLUE_COLOR}${1:-} ${DEFAULT}"
}
log_warning() {
YELLOW_COLOR="\033[33m"
echo -e "${YELLOW_COLOR}${1:-} ${DEFAULT}"
}
log_error() {
RED_COLOR="\033[0;31m"
echo -e "${RED_COLOR}${1:-}${DEFAULT}"
}
local msg_type
local msg
msg_type=$(echo "$@"|cut -d" " -f1)
msg="$(echo "$@"|cut -d" " -f2-)"
msg="$(date "+%Y-%m-%d %H:%M:%S %Z") [$msg_type] [$$] $msg"
case "$msg_type" in
'NOTICE') log_notice "$msg" | tee -a "$LOGFILE" ;;
'INFO') log_info "$msg" | tee -a "$LOGFILE" ;;
'WARNING') log_warning "$msg" | tee -a "$LOGFILE" ;;
'ERROR') log_error "$msg" | tee -a "$LOGFILE" ;;
*) echo "$msg" | tee -a "$LOGFILE" ;;
esac
}
log "NOTICE some notice level message"
log "INFO some info message"
log "WARNING some warning message"
log "ERROR some error message"
log "DEBUG (catch-all) some debug message"
log "This is an incorrectly formatted message"
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment