Files
tyapi-server/scripts/log-manager.sh

154 lines
3.5 KiB
Bash
Raw Normal View History

2025-07-28 13:47:58 +08:00
#!/bin/bash
# 日志管理脚本
# 用于清理旧日志文件和查看日志统计信息
LOG_DIR="./logs"
RETENTION_DAYS=30
# 颜色定义
RED='\033[0;31m'
GREEN='\033[0;32m'
YELLOW='\033[1;33m'
BLUE='\033[0;34m'
NC='\033[0m' # No Color
# 打印带颜色的消息
print_info() {
echo -e "${BLUE}[INFO]${NC} $1"
}
print_success() {
echo -e "${GREEN}[SUCCESS]${NC} $1"
}
print_warning() {
echo -e "${YELLOW}[WARNING]${NC} $1"
}
print_error() {
echo -e "${RED}[ERROR]${NC} $1"
}
# 显示帮助信息
show_help() {
echo "日志管理脚本"
echo ""
echo "用法: $0 [命令]"
echo ""
echo "命令:"
echo " clean - 清理超过 $RETENTION_DAYS 天的旧日志文件"
echo " stats - 显示日志统计信息"
echo " size - 显示日志目录大小"
echo " list - 列出所有日志文件"
echo " help - 显示此帮助信息"
echo ""
echo "示例:"
echo " $0 clean # 清理旧日志"
echo " $0 stats # 查看统计信息"
}
# 清理旧日志文件
clean_old_logs() {
print_info "开始清理超过 $RETENTION_DAYS 天的旧日志文件..."
if [ ! -d "$LOG_DIR" ]; then
print_error "日志目录 $LOG_DIR 不存在"
return 1
fi
# 查找并删除超过指定天数的日志文件
find "$LOG_DIR" -name "*.log*" -type f -mtime +$RETENTION_DAYS -exec rm -f {} \;
# 删除空的日期目录
find "$LOG_DIR" -type d -empty -delete
print_success "旧日志文件清理完成"
}
# 显示日志统计信息
show_stats() {
print_info "日志统计信息:"
echo ""
if [ ! -d "$LOG_DIR" ]; then
print_error "日志目录 $LOG_DIR 不存在"
return 1
fi
# 总文件数
total_files=$(find "$LOG_DIR" -name "*.log*" -type f | wc -l)
echo "总日志文件数: $total_files"
# 总大小
total_size=$(du -sh "$LOG_DIR" 2>/dev/null | cut -f1)
echo "日志目录总大小: $total_size"
# 按日期统计
echo ""
echo "按日期统计:"
for date_dir in "$LOG_DIR"/*/; do
if [ -d "$date_dir" ]; then
date_name=$(basename "$date_dir")
file_count=$(find "$date_dir" -name "*.log*" -type f | wc -l)
dir_size=$(du -sh "$date_dir" 2>/dev/null | cut -f1)
echo " $date_name: $file_count 个文件, $dir_size"
fi
done
# 最近修改的文件
echo ""
echo "最近修改的日志文件:"
find "$LOG_DIR" -name "*.log*" -type f -exec ls -lh {} \; | head -5
}
# 显示日志目录大小
show_size() {
if [ ! -d "$LOG_DIR" ]; then
print_error "日志目录 $LOG_DIR 不存在"
return 1
fi
total_size=$(du -sh "$LOG_DIR" 2>/dev/null | cut -f1)
print_info "日志目录大小: $total_size"
}
# 列出所有日志文件
list_logs() {
if [ ! -d "$LOG_DIR" ]; then
print_error "日志目录 $LOG_DIR 不存在"
return 1
fi
print_info "所有日志文件:"
find "$LOG_DIR" -name "*.log*" -type f -exec ls -lh {} \;
}
# 主函数
main() {
case "$1" in
"clean")
clean_old_logs
;;
"stats")
show_stats
;;
"size")
show_size
;;
"list")
list_logs
;;
"help"|"-h"|"--help"|"")
show_help
;;
*)
print_error "未知命令: $1"
show_help
exit 1
;;
esac
}
# 执行主函数
main "$@"