Skip to content

Instantly share code, notes, and snippets.

@efim-a-efim
Created April 2, 2014 09:51
Show Gist options
  • Save efim-a-efim/9931171 to your computer and use it in GitHub Desktop.
Save efim-a-efim/9931171 to your computer and use it in GitHub Desktop.
Complex Bash log routine. May log to files and stdout. Supports messages stream from STDIN.
#!/bin/sh
log() {
local _opt=''
local _date="`date -R`"
local _log_tag="`basename $0`"
local _level='${LOG_LEVEL:-debug}'
local _print=0
local _log_path="${LOG_PATH:-/tmp}"
local _log_facility="${LOG_FACILITY:-local1}"
local _runtime="`date '+%Y-%m-%d-%H-%M-%S'`"
while getopts ':f:l:p:t:o' _opt; do
case "${_opt}" in
f)
_log_tag="${_log_tag}.${OPTARG}"
;;
l)
_level="${OPTARG}"
;;
o)
_print=1
;;
p)
_log_path="${OPTARG}"
;;
t)
_runtime="${OPTARG}"
;;
*)
;;
esac
done
shift shift $((${OPTIND}-1))
local _rec="$1"
if [[ "${_rec}" ]]; then
# log message given
if [[ "${_log_path}" == "syslog" ]]; then
#statements
logger -p "${_log_facility}.${_level}" -t "${_log_tag}" -i "${_rec}" >/dev/null 2>&1
# Print message to STDOUT
[[ ${_print} -gt 0 ]] && echo "${_date} `hostname` ${_log_tag}[$$]: ${_log_facility}.${_level} ${_rec}"
elif [[ "${_log_path}" == '' ]]; then
echo "${_date} `hostname` ${_log_tag}[$$]: ${_log_facility}.${_level} ${_rec}"
else
# create logs path
[ ! -d "${_log_path}" ] && mkdir -p "${_log_path}"
echo "${_date} `hostname` ${_log_tag}[$$]: ${_log_facility}.${_level} ${_rec}" >>"${_log_path}/${_runtime}.log"
[[ ${_print} -gt 0 ]] && echo "${_date} `hostname` ${_log_tag}[$$]: ${_log_facility}.${_level} ${_rec}"
fi
else
# log from STDIN
while read _rec; do
if [[ "${_log_path}" == "syslog" ]]; then
#statements
logger -p "${_log_facility}.${_level}" -t "${_log_tag}" -i "${_rec}" >/dev/null 2>&1
[[ ${_print} -gt 0 ]] && echo "${_date} `hostname` ${_log_tag}[$$]: ${_log_facility}.${_level} ${_rec}"
elif [[ "${_log_path}" == '' ]]; then
echo "${_date} `hostname` ${_log_tag}[$$]: ${_log_facility}.${_level} ${_rec}"
else
# create logs path
[ ! -d "${_log_path}" ] && mkdir -p "${_log_path}"
echo "${_date} `hostname` ${_log_tag}[$$]: ${_log_facility}.${_level} ${_rec}" >> "${_log_path}/${_runtime}.log"
[[ ${_print} -gt 0 ]] && echo "${_date} `hostname` ${_log_tag}[$$]: ${_log_facility}.${_level} ${_rec}"
fi
done
fi
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment