Skip to content

Instantly share code, notes, and snippets.

@atom-tr
Last active October 19, 2023 02:37
Show Gist options
  • Save atom-tr/4966c70f369401125f55c41e8f7b24fa to your computer and use it in GitHub Desktop.
Save atom-tr/4966c70f369401125f55c41e8f7b24fa to your computer and use it in GitHub Desktop.
πŸ‘» Easy Console Logging .sh
πŸ’– Easy to writing outputs to log file and console
πŸ’ͺ Enhance display for log level in console

Example

  1. Include logging to script
dir="`dirname \"$0\"`"
source $dir/functions/logging.sh

or

source <(curl -s https://gist.githubusercontent.com/atom-tr/4966c70f369401125f55c41e8f7b24fa/raw/9b6902e7b5f32460043f1a223b5ab343bb46c26d/logging.sh)
  1. [Option] Start writing logs to a special file.

If use this, logs will be print console and write logs to file

basename=`basename $0` # Get script name
log="$dir/logs/${basename%.*}.log" # Get log file path
start_write_log $log # this will start writing logs to file
  1. Use
logging "Start script $0"

log.info "Getting info ... "

raise_error "exists!";
#!/bin/bash
#### INFO ####
# Author: thai.tv - thai.tv@netnam.vn
# Github: github.com/atom-tr
# You can use these ANSI escape codes:
# http://misc.flogisoft.com/bash/tip_colors_and_formatting
# Black 0;30 Dark Gray 1;30
# Red 0;31 Light Red 1;31
# Green 0;32 Light Green 1;32
# Brown/Orange 0;33 Yellow 1;33
# Blue 0;34 Light Blue 1;34
# Purple 0;35 Light Purple 1;35
# Cyan 0;36 Light Cyan 1;36
# Light Gray 0;37 White 1;37
reset_='\e[0m'
TAB="$(printf '\t')"
export LOGGING_EOL=false
start_write_log() { # Make echo and logging to file
DIR="$(dirname "${1}")"
[ ! -d "${DIR}" ] && mkdir -p "${DIR}"
# redirect messages to file descriptor 3
touch ${1} && exec 3>>${1} 2>&1
}
log.write() {
if { >&3; } 2> /dev/null; then
[ "$LOGGING_EOL" == true ] && l__="$1" || l__="$(date +"%F %T") $2: $1"
echo -e "$l__" >&3
fi
export LOGGING_EOL=false
}
logging() { echo -e "$1";log.write "$1" "NOTSET"; }
log.debug() { echo -e "$1";log.write "$1" "DEBUG"; }
log.info() { # Cyan
echo -e "\e[96m$1${reset_}"
log.write "$1" "INFO"
}
log.secondary() { # Gray
echo -e "\033[1;33m$1${reset_}"
log.write "$1" "DEBUG"
}
log.success() { # Green
echo -e "\e[32m$1${reset_}"
log.write "$1" "SUCCESS"
}
log.warning() { # Yellow
echo -e "\e[33m$1${reset_}"
log.write "$1" "WARNING"
}
log.error() { # Red
echo -e "\n\033[1;31m$1\e[0m\n"
log.write "$1" "ERROR"
}
raise_error() { log.error "$1"; exit 1; }
log.ne() { # No end line
export LOGGING_EOL=true && echo -ne "$1"
if { >&3; } 2> /dev/null; then
echo -ne "$(date +"%F %T") NOTSET: $1" >&3
fi
}
log.d() { log.debug "$1"; }
log.i() { log.info "$1"; }
log.s() { log.success "$1"; }
log.w() { log.warning "$1"; }
log.e() { log.error "$1"; }
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment