根据docker服务保存日志脚本,时间可选版本

bash 复制代码
#!/bin/bash

# 获取docker ps输出,提取容器ID和名称,并存入数组
container_ids=($(docker ps -q))
container_names=($(docker ps --format '{{.Names}}'))

# 检查是否有运行中的容器
if [ ${#container_ids[@]} -eq 0 ]; then
    echo "No running containers found."
    exit 1
fi

# 显示容器列表供用户选择
echo "Running containers:"
for i in "${!container_ids[@]}"; do
    echo "[$i] ${container_names[$i]} (${container_ids[$i]})"
done

# 请求用户选择容器
read -p "Enter the index of the container to view logs: " choice

# 验证用户输入是否为有效数字
re='^[0-9]+$'
if ! [[ $choice =~ $re ]]; then
   echo "Error: Invalid input, please enter a number."
   exit 1
fi

# 验证用户选择是否在范围内
if (( choice < 0 || choice >= ${#container_ids[@]} )); then
    echo "Error: Index out of range."
    exit 1
fi

# 获取用户选择的容器ID和名称
selected_container_id="${container_ids[$choice]}"
selected_container_name="${container_names[$choice]}"

# 功能选择菜单
echo ""
echo "Select an option:"
echo "[1] View logs in terminal"
echo "[2] Save logs to file"
read -p "Enter your choice (1 or 2): " option

case $option in
    1)
        # 查看日志功能
        read -p "Enter the number of lines to display (default is 1000): " lines
        lines=${lines:-1000}

        read -p "Enter a keyword to search for in the logs (leave empty for no search): " keyword

        if [ -z "$keyword" ]; then
            docker logs -f --tail "$lines" "$selected_container_id"
        else
            docker logs -f --tail "$lines" "$selected_container_id" | grep "$keyword"
        fi
        ;;
    2)
        # 保存日志功能
        echo ""
        echo "Save log options:"
        echo "[1] Last 2 days (default)"
        echo "[2] Last 24 hours"
        echo "[3] Last 7 days"
        echo "[4] Custom hours"
        echo "[5] All logs (since container start)"
        read -p "Enter your choice (1-5): " time_option

        case $time_option in
            1|"")
                # 最近2天 = 48小时
                since_time="48h"
                since_display="2 days (48 hours)"
                ;;
            2)
                since_time="24h"
                since_display="24 hours"
                ;;
            3)
                since_time="168h"
                since_display="7 days (168 hours)"
                ;;
            4)
                read -p "Enter number of hours: " custom_hours
                since_time="${custom_hours}h"
                since_display="${custom_hours} hours"
                ;;
            5)
                since_time=""
                since_display="all logs (since container start)"
                ;;
            *)
                echo "Invalid option, using default (2 days)"
                since_time="48h"
                since_display="2 days (48 hours)"
                ;;
        esac

        # 生成文件名
        timestamp=$(date +"%Y%m%d_%H%M%S")
        filename="${selected_container_name}_logs_${timestamp}.log"
        
        echo "Saving logs for container: $selected_container_name"
        echo "Time range: $since_display"
        echo "File: $filename"
        echo ""

        # 保存日志(根据是否指定时间范围使用不同的命令)
        if [ -z "$since_time" ]; then
            docker logs "$selected_container_id" > "$filename"
        else
            docker logs --since "$since_time" "$selected_container_id" > "$filename"
        fi
        
        if [ $? -eq 0 ]; then
            echo "Logs successfully saved to: $filename"
            echo "File size: $(du -h "$filename" | cut -f1)"
            echo "Lines saved: $(wc -l < "$filename")"
        else
            echo "Error: Failed to save logs"
            # 清理可能创建的空文件
            if [ -f "$filename" ] && [ ! -s "$filename" ]; then
                rm "$filename"
            fi
            exit 1
        fi
        ;;
    *)
        echo "Invalid option selected"
        exit 1
        ;;
esac

正确的时间格式:Docker logs 的 --since 参数支持以下格式:

10m - 10分钟

2h - 2小时

30h - 30小时

2007-01-02T15:04:05 - 具体时间戳

提供多个预设选项:

2天 = 48小时

24小时

7天 = 168小时

自定义小时数

所有日志

更好的错误处理:如果保存失败,会清理空文件

Docker logs --since 支持的格式:

10m - 10分钟前到现在

1h30m - 1小时30分钟前到现在

2h - 2小时前到现在

2013-01-02T13:23:37 - 从特定时间点开始

现在脚本应该能正常工作,不会出现时间格式错误了!

相关推荐
oMcLin4 分钟前
如何在 CentOS 7.9 上配置并调优 Docker Swarm 集群,确保跨多个节点的高效服务发现与负载均衡?
docker·centos·服务发现
鱼跃鹰飞5 分钟前
经典面试题:K8S的自动缩扩容和崩溃恢复
java·容器·kubernetes
江湖有缘7 分钟前
Fenrus + Docker 实战:构建简洁高效的浏览器新标签页
运维·docker·容器
乾元7 分钟前
如何把 CCIE / HCIE 的实验案例改造成 AI 驱动的工程项目——从“实验室能力”到“可交付系统”的完整迁移路径
大数据·运维·网络·人工智能·深度学习·安全·机器学习
lpfasd1239 分钟前
宝塔面板(BT Panel)集成雷池 SafeLine WAF(社区版)
运维
weixin_4462608510 分钟前
XPipe: 轻松访问你的服务器基础设施 [特殊字符]
运维·服务器
TTGGGFF11 分钟前
GLM-4V-9B 视觉多模态模型本地部署教程【保姆级教程】
linux·运维·服务器·图文对话
r***013812 分钟前
Nginx代理到https地址忽略证书验证配置
运维·nginx·https
xiaobaishuoAI15 分钟前
后端工程化实战指南:从规范到自动化,打造高效协作体系
java·大数据·运维·人工智能·maven·devops·geo
Hello.Reader30 分钟前
PyFlink Configuration 一次讲透怎么配、配哪些、怎么“调得快且稳”
运维·服务器·python·flink