shell脚本设置日志格式
1.封装函数 #!/bin/bash function log() { echo "$@" } //测试: log "this is a test..." log "today is `date '+%Y-%m-%d'` " 2.设置时间日志 #!/bin/bash function log() { echo "$(date '+%Y-%m-%d %H:%M:%S') $@" } log "this is a test..." 3.设置日志级别,并输出对应日志 #!/bin/bash #日志级别 debug-1, info-2, warn-3, error-4, always-5 LOG_LEVEL=3 #调试日志 function log_debug(){ content="[DEBUG] $(date '+%Y-%m-%d %H:%M:%S') $@" [ $LOG_LEVEL -le 1 ] && echo -e "\033[32m" ${content} "\033[0m" } #信息日志 function log_info(){ content="[INFO] $(date '+%Y-%m-%d %H:%M:%S') $@" [ $LOG_LEVEL -le 2 ] && echo -e "\033[32m" ${content} "\033[0m" } #警告日志 function log_warn(){ content="[WARN] $(date '+%Y-%m-%d %H:%M:%S') $@" [ $LOG_LEVEL -le 3 ] && echo -e "\033[33m" ${content} "\033[0m" } #错误日志 function log_err(){ content="[ERROR] $(date '+%Y-%m-%d %H:%M:%S') $@" [ $LOG_LEVEL -le 4 ] && echo -e "\033[31m" ${content} "\033[0m" } #一直都会打印的日志 function log_always(){ content="[ALWAYS] $(date '+%Y-%m-%d %H:%M:%S') $@" [ $LOG_LEVEL -le 5 ] && echo -e "\033[32m" ${content} "\033[0m" } 4.日志写入文件 #日志文件 LOG_FILE=./log.txt function log(){ content="$(date '+%Y-%m-%d %H:%M:%S') $@" echo $content >> $LOG_FILE }
5.改良后的日志输出
#主要是上边的全颜色输出,有点不好看,现在只是日志级别输出颜色 [root@localhost shell]# cat shell_log.sh #!/bin/bash #日志级别 debug-1, info-2, warn-3, error-4, always-5 LOG_LEVEL=2 #调试日志 function log_debug(){ content="$(date '+%Y-%m-%d %H:%M:%S')" [ $LOG_LEVEL -le 1 ] && echo -e "${content} \033[32m"[DEBUG]"\033[0m $@" } #信息日志 function log_info(){ content="$(date '+%Y-%m-%d %H:%M:%S')" [ $LOG_LEVEL -le 2 ] && echo -e "${content} \033[32m"[INFO]"\033[0m $@" } #警告日志 function log_warn(){ content="$(date '+%Y-%m-%d %H:%M:%S')" [ $LOG_LEVEL -le 3 ] && echo -e "${content} \033[33m"[WARN]"\033[0m $@" } #错误日志 function log_err(){ content="$(date '+%Y-%m-%d %H:%M:%S')" [ $LOG_LEVEL -le 4 ] && echo -e "${content} \033[31m"[ERROR]"\033[0m $@" } #一直都会打印的日志 function log_always(){ content="$(date '+%Y-%m-%d %H:%M:%S')" [ $LOG_LEVEL -le 5 ] && echo -e "${content} \033[32m"[ALWAYS]"\033[0m $@" } log_debug "this is my dog" log_info "this is my dog" log_warn "this is my dog" log_err "this is my dog" log_always "this is my dog"