Use syslog for logging if available

This commit is contained in:
Janek Bevendorff 2016-11-17 02:45:22 +01:00
parent 4b84ad5997
commit 0f1b35e57c
1 changed files with 41 additions and 19 deletions

View File

@ -119,8 +119,26 @@ write_log() {
local log_msg local log_msg
local log_date local log_date
local log_dest local log_dest
local use_syslog=false
local logger="logger -t $(basename $0)"
command -v logger > /dev/null 2>&1
if [ $? -eq 0 ]; then
use_syslog=true
fi
if [ $1 -gt 0 ] && [ $1 -le $LOG_LEVEL ]; then if [ $1 -gt 0 ] && [ $1 -le $LOG_LEVEL ]; then
if $use_syslog; then
log_msg="${2}"
case $1 in
1) $logger -p err "${log_msg}" ;;
2) $logger -p warning "${log_msg}" ;;
3) $logger -p info "${log_msg}" ;;
*) $logger -p debug "${log_msg}" ;;
esac
fi
# prepend priority prefixes to message for further logging output
case $1 in case $1 in
1) log_msg="ERROR: ${2}" ;; 1) log_msg="ERROR: ${2}" ;;
2) log_msg="WARNING: ${2}" ;; 2) log_msg="WARNING: ${2}" ;;
@ -128,27 +146,31 @@ write_log() {
*) log_msg="DEBUG: ${2}" ;; *) log_msg="DEBUG: ${2}" ;;
esac esac
log_date="[$(date)]" # if no syslog facility exists, go the cumbersome way...
full_log_msg="${log_date} ${log_msg}" if ! $use_syslog; then
log_date="[$(date)]"
if [ "${_FORCED_LOG_FILE}" != "" ]; then full_log_msg="${log_date} ${log_msg}"
log_dest=${_FORCED_LOG_FILE}
elif [ $(id -u) -eq 0 ]; then if [ "${_FORCED_LOG_FILE}" != "" ]; then
log_dest=${LOG_FILE} log_dest=${_FORCED_LOG_FILE}
elif [ "${HOME}" != "" ] && [ "${USER_LOG_FILE}" != "" ]; then elif [ $(id -u) -eq 0 ]; then
log_dest=${HOME}/${USER_LOG_FILE} log_dest=${LOG_FILE}
else elif [ "${HOME}" != "" ] && [ "${USER_LOG_FILE}" != "" ]; then
echo "WARNING: Couldn't determine valid log file location, using '/var/tmp'..." >&2 log_dest=${HOME}/${USER_LOG_FILE}
log_dest="/var/tmp/${LOG_FILE}" else
fi echo "WARNING: Couldn't determine valid log file location, using '/var/tmp'..." >&2
log_dest="/var/tmp/${LOG_FILE}"
if ! test_file_perms "w" "${log_dest}"; then fi
echo "ERROR: Couldn't open log file for writing, redirecting to STDOUT!" >&2
echo "${log_date} ${log_msg}" >&1 if ! test_file_perms "w" "${log_dest}"; then
else echo "ERROR: Couldn't open log file for writing, redirecting to STDOUT!" >&2
echo "${log_date} ${log_msg}" >> "${log_dest}" echo "${log_date} ${log_msg}" >&1
else
echo "${log_date} ${log_msg}" >> "${log_dest}"
fi
fi fi
# after logging stuff, print it to the screen if we're not in quiet mode
if ! $_QUIET_MODE && [ $1 -eq 1 ]; then if ! $_QUIET_MODE && [ $1 -eq 1 ]; then
$_VERBOSE_MODE || $PRINT_ERRORS && echo "${log_msg}" >&2 $_VERBOSE_MODE || $PRINT_ERRORS && echo "${log_msg}" >&2
elif ! $_QUIET_MODE && [ $1 -le 2 ]; then elif ! $_QUIET_MODE && [ $1 -le 2 ]; then