logToFile.sh

gself發表於2019-02-22
#!/usr/bin/env bash
#log path is /var/log/yanke_shell_log.log
# Version:      1.1
# Update date:  20180320

if [ -d /var/log ]
then
    echo '/var/log/ exists...'
else
    mkdir -pv /var/log/
fi

# Default log file is /var/log/yanke_shell_log.`date +%F`
if [ `echo "${LOG_FILE}"| grep -v ^$| wc -l` -eq 0 ]; then
  LOG_FILE=/var/log/yanke_shell_log.log
fi

echo "Default LOG_FILE is ${LOG_FILE}"

function log_info () {
DATE_N=`date "+%Y-%m-%d %H:%M:%S"`
USER_N=`whoami`
echo "${DATE_N} ${USER_N} execute $0 [INFO] $@" >> ${LOG_FILE} #執行成功日誌列印路徑
}

function log_error () {
DATE_N=`date "+%Y-%m-%d %H:%M:%S"`
USER_N=`whoami`
echo -e "\a"
echo -e "\033[41;37m ${DATE_N} ${USER_N} execute $0 [ERROR] $@ \033[0m"  >> ${LOG_FILE} #執行失敗日誌列印路徑
}

function fn_log () {
if [  $? -eq 0  ]
then
    log_info "$@ successed."
    echo -e "\033[32m $@ sucessed. \033[0m"
else
    log_error "$@ failed."
    echo -e "\033[41;37m $@ failed. \033[0m"
    exit 1
fi
}

# trap 'fn_log "DO NOT SEND CTR + C WHEN EXECUTE SCRIPT !!!! "'  2
複製程式碼