79 lines
1.7 KiB
Bash
79 lines
1.7 KiB
Bash
#!/bin/bash
|
|
|
|
# 日志级别定义
|
|
LOG_LEVEL_DEBUG=10
|
|
LOG_LEVEL_INFO=20
|
|
LOG_LEVEL_WARNING=30
|
|
LOG_LEVEL_ERROR=40
|
|
|
|
# 当前日志级别
|
|
CURRENT_LOG_LEVEL=$LOG_LEVEL_INFO
|
|
|
|
# 颜色定义
|
|
COLOR_RESET="\033[0m"
|
|
COLOR_DEBUG="\033[0;36m"
|
|
COLOR_INFO="\033[0;32m"
|
|
COLOR_WARNING="\033[0;33m"
|
|
COLOR_ERROR="\033[0;31m"
|
|
|
|
# 日志函数
|
|
log() {
|
|
local level=$1
|
|
shift
|
|
local message="$*"
|
|
local timestamp=$(date +"%Y-%m-%d %H:%M:%S")
|
|
local color=$COLOR_RESET
|
|
|
|
if [ "$level" -ge "$CURRENT_LOG_LEVEL" ]; then
|
|
case $level in
|
|
$LOG_LEVEL_DEBUG)
|
|
color=$COLOR_DEBUG
|
|
;;
|
|
$LOG_LEVEL_INFO)
|
|
color=$COLOR_INFO
|
|
;;
|
|
$LOG_LEVEL_WARNING)
|
|
color=$COLOR_WARNING
|
|
;;
|
|
$LOG_LEVEL_ERROR)
|
|
color=$COLOR_ERROR
|
|
;;
|
|
esac
|
|
echo -e "${color}[$timestamp] [${level}] $message${COLOR_RESET}"
|
|
fi
|
|
}
|
|
|
|
# 帮助函数
|
|
show_help() {
|
|
echo "Usage: $0 [options]"
|
|
echo "Options:"
|
|
echo " -h, --help Show this help message and exit"
|
|
echo " -v, --verbose Set log level to debug"
|
|
}
|
|
|
|
# 解析命令行参数
|
|
while [[ "$#" -gt 0 ]]; do
|
|
case $1 in
|
|
-h|--help)
|
|
show_help
|
|
exit 0
|
|
;;
|
|
-v|--verbose)
|
|
CURRENT_LOG_LEVEL=$LOG_LEVEL_DEBUG
|
|
shift
|
|
;;
|
|
*)
|
|
echo "Unknown parameter passed: $1"
|
|
show_help
|
|
exit 1
|
|
;;
|
|
esac
|
|
shift
|
|
done
|
|
|
|
# 示例日志记录
|
|
log $LOG_LEVEL_INFO "Script started"
|
|
log $LOG_LEVEL_DEBUG "This is a debug message"
|
|
log $LOG_LEVEL_WARNING "This is a warning message"
|
|
log $LOG_LEVEL_ERROR "This is an error message"
|