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
}
shell脚本输出格式化日志信息
#!/bin/bash
#${FUNCNAME[1]代表调用该函数的函数,$LINENO代表当前代码行号
Log(){
local log_level=$1
local log_info=$2
local line=$3
local script_name=$(basename $0)
case ${log_level} in
"INFO")
echo -e "\033[32m$(date "+%Y-%m-%d %T.%N") [INFO]: ${log_info}\033[0m";;
"WARN")
echo -e "\033[33m$(date "+%Y-%m-%d %T.%N") [WARN]: ${log_info}\033[0m";;
"ERROR")
echo -e "\033[31m$(date "+%Y-%m-%d %T.%N") [ERROR ${script_name} ${FUNCNAME[1]}:$line]: ${log_info}\033[0m";;
*)
echo -e "${@}"
;;
esac
}
Log INFO "Install Success"
Log WARN "You Can Ignore"
Log ERROR "Invalid Param" $LINENO
到此这篇关于shell脚本设置日志格式的文章就介绍到这了,更多相关shell日志格式内容请搜索aitechtogether.com以前的文章或继续浏览下面的相关文章希望大家以后多多支持aitechtogether.com!