Shell脚本如何监控API接口响应时间

wen 实用脚本 1

本文目录导读:

Shell脚本如何监控API接口响应时间

  1. 直接运行
  2. 后台运行

我可以为您提供一个Shell脚本示例来监控API接口的响应时间,这个脚本会记录每个请求的响应时间和状态码,并将结果输出到日志文件。

基础监控脚本

#!/bin/bash
# API监控脚本 - 监控API响应时间
# 配置参数
API_URL="https://api.example.com/health"  # 要监控的API地址
LOG_FILE="/var/log/api_monitor.log"       # 日志文件路径
INTERVAL=60                               # 监控间隔(秒)
TIMEOUT=30                                # 请求超时时间(秒)
THRESHOLD=5                               # 响应时间告警阈值(秒)
# 创建日志目录(如果不存在)
mkdir -p "$(dirname "$LOG_FILE")"
# 日志函数
log_message() {
    local level=$1
    local message=$2
    local timestamp=$(date "+%Y-%m-%d %H:%M:%S")
    echo "[$timestamp] [$level] $message" >> "$LOG_FILE"
    echo "[$timestamp] [$level] $message"
}
# 监控函数
monitor_api() {
    log_message "INFO" "开始监控 API: $API_URL"
    while true; do
        # 记录开始时间
        start_time=$(date +%s%N)
        # 发送请求并获取HTTP状态码
        http_code=$(curl -o /dev/null -s -w "%{http_code}" \
            --connect-timeout $TIMEOUT \
            --max-time $TIMEOUT \
            "$API_URL" 2>/dev/null)
        curl_exit_code=$?
        # 记录结束时间
        end_time=$(date +%s%N)
        # 计算响应时间(毫秒)
        response_time=$(( (end_time - start_time) / 1000000 ))
        # 获取当前时间戳
        current_time=$(date "+%Y-%m-%d %H:%M:%S")
        # 检查请求是否成功
        if [ $curl_exit_code -eq 0 ]; then
            # 检查响应时间是否超过阈值
            if [ $response_time -gt $((THRESHOLD * 1000)) ]; then
                log_message "WARNING" "响应时间过长: ${response_time}ms (状态码: $http_code)"
            else
                log_message "INFO" "请求成功: ${response_time}ms (状态码: $http_code)"
            fi
            # 输出到标准输出(便于其他程序处理)
            echo "$current_time,$response_time,$http_code"
        else
            # 处理curl错误
            case $curl_exit_code in
                6)  error_msg="无法解析主机" ;;
                7)  error_msg="连接被拒绝" ;;
                28) error_msg="请求超时" ;;
                *)  error_msg="curl错误代码: $curl_exit_code" ;;
            esac
            log_message "ERROR" "请求失败: $error_msg"
            echo "$current_time,ERROR,$error_msg"
        fi
        # 等待指定间隔
        sleep $INTERVAL
    done
}
# 主函数
main() {
    echo "API响应时间监控脚本"
    echo "=================="
    echo "监控目标: $API_URL"
    echo "监控间隔: ${INTERVAL}秒"
    echo "告警阈值: ${THRESHOLD}秒"
    echo "日志文件: $LOG_FILE"
    echo "=================="
    # 检查curl是否安装
    if ! command -v curl &> /dev/null; then
        log_message "ERROR" "curl未安装,请先安装curl"
        exit 1
    fi
    # 捕获Ctrl+C信号
    trap 'log_message "INFO" "监控脚本已停止"; exit 0' SIGINT
    # 开始监控
    monitor_api
}
# 执行主函数
main

高级监控脚本(带统计功能)

#!/bin/bash
# 高级API监控脚本 - 带统计和告警功能
# 配置参数(可通过命令行参数覆盖)
API_URL="${1:-https://api.example.com/health}"
INTERVAL="${2:-60}"
LOG_FILE="/var/log/api_monitor_advanced.log"
STATS_FILE="/tmp/api_stats.json"
THRESHOLD_SLOW=3    # 慢响应阈值(秒)
THRESHOLD_ERROR=5   # 连续错误阈值
# 初始化计数器
total_requests=0
successful_requests=0
failed_requests=0
slow_requests=0
consecutive_errors=0
total_response_time=0
# 日志函数
log_message() {
    local level=$1
    local message=$2
    local timestamp=$(date "+%Y-%m-%d %H:%M:%S")
    echo "[$timestamp] [$level] $message" | tee -a "$LOG_FILE"
}
# 统计信息更新
update_stats() {
    local response_time=$1
    local status=$2
    total_requests=$((total_requests + 1))
    total_response_time=$((total_response_time + response_time))
    if [ "$status" = "success" ]; then
        successful_requests=$((successful_requests + 1))
        consecutive_errors=0
    else
        failed_requests=$((failed_requests + 1))
        consecutive_errors=$((consecutive_errors + 1))
    fi
    if [ $response_time -gt $((THRESHOLD_SLOW * 1000)) ] && [ "$status" = "success" ]; then
        slow_requests=$((slow_requests + 1))
    fi
}
# 打印统计信息
print_stats() {
    echo ""
    log_message "INFO" "========== 监控统计 =========="
    log_message "INFO" "总请求数: $total_requests"
    log_message "INFO" "成功请求: $successful_requests"
    log_message "INFO" "失败请求: $failed_requests"
    log_message "INFO" "慢响应请求: $slow_requests"
    if [ $total_requests -gt 0 ]; then
        avg_response_time=$((total_response_time / total_requests))
        success_rate=$(( (successful_requests * 100) / total_requests ))
        log_message "INFO" "平均响应时间: ${avg_response_time}ms"
        log_message "INFO" "成功率: ${success_rate}%"
    fi
    log_message "INFO" "============================="
    # 保存统计信息到JSON文件
    cat > "$STATS_FILE" << EOF
{
    "timestamp": "$(date -Iseconds)",
    "total_requests": $total_requests,
    "successful_requests": $successful_requests,
    "failed_requests": $failed_requests,
    "slow_requests": $slow_requests,
    "avg_response_time_ms": $avg_response_time,
    "success_rate": $success_rate
}
EOF
}
# 检查告警条件
check_alerts() {
    local response_time=$1
    local http_code=$2
    # 检查连续错误
    if [ $consecutive_errors -ge $THRESHOLD_ERROR ]; then
        log_message "CRITICAL" "连续${consecutive_errors}次请求失败!API可能已宕机"
        # 这里可以添加发送告警的逻辑(邮件、短信等)
        # send_alert "API可能已宕机"
    fi
    # 检查响应时间
    if [ $response_time -gt $((THRESHOLD_SLOW * 1000)) ]; then
        log_message "WARNING" "响应时间异常: ${response_time}ms (阈值: ${THRESHOLD_SLOW}s)"
    fi
    # 检查HTTP状态码
    if [ "$http_code" != "200" ] && [ "$http_code" != "201" ] && [ "$http_code" != "204" ]; then
        log_message "WARNING" "非正常HTTP状态码: $http_code"
    fi
}
# 主监控循环
monitor_api() {
    log_message "INFO" "开始高级API监控 (间隔: ${INTERVAL}s)"
    while true; do
        # 获取响应时间
        start_time=$(date +%s%N)
        # 使用curl发送请求,获取详细的响应信息
        response=$(curl -o /dev/null -s -w "%{http_code}:%{time_total}" \
            --connect-timeout 30 \
            --max-time 30 \
            "$API_URL" 2>&1)
        curl_exit_code=$?
        end_time=$(date +%s%N)
        response_time=$(( (end_time - start_time) / 1000000 ))
        if [ $curl_exit_code -eq 0 ]; then
            # 解析响应数据
            http_code=$(echo "$response" | cut -d: -f1)
            time_total=$(echo "$response" | cut -d: -f2)
            # 更新统计信息
            update_stats $response_time "success"
            # 检查告警条件
            check_alerts $response_time $http_code
            # 记录正常请求
            log_message "INFO" "API响应: ${time_total}s (HTTP $http_code)"
        else
            # 处理错误
            update_stats 0 "failed"
            check_alerts 0 "ERROR"
            log_message "ERROR" "API请求失败 (curl错误码: $curl_exit_code)"
        fi
        # 每10次请求打印一次统计信息
        if [ $((total_requests % 10)) -eq 0 ] && [ $total_requests -gt 0 ]; then
            print_stats
        fi
        sleep $INTERVAL
    done
}
# 清理函数
cleanup() {
    log_message "INFO" "监控脚本停止"
    print_stats
    exit 0
}
# 设置信号处理
trap cleanup SIGINT SIGTERM
# 主程序入口
main() {
    echo "=================================="
    echo "高级API响应时间监控 v2.0"
    echo "=================================="
    echo "监控目标: $API_URL"
    echo "监控间隔: ${INTERVAL}秒"
    echo "慢响应阈值: ${THRESHOLD_SLOW}秒"
    echo "连续错误阈值: ${THRESHOLD_ERROR}"
    echo "日志文件: $LOG_FILE"
    echo "统计文件: $STATS_FILE"
    echo "=================================="
    # 检查依赖
    if ! command -v curl &> /dev/null; then
        log_message "ERROR" "缺少curl命令"
        exit 1
    fi
    # 开始监控
    monitor_api
}
# 执行主程序
main

使用方法

  1. 基本使用
    # 保存脚本为 api_monitor.sh
    chmod +x api_monitor.sh

直接运行

./api_monitor.sh

后台运行

nohup ./api_monitor.sh &


2. **高级脚本使用**:
```bash
# 自定义参数
./api_monitor_advanced.sh "https://your-api.com/health" 30
  1. 查看日志
    tail -f /var/log/api_monitor.log

功能特点

  • 实时监控:按指定间隔持续监控API响应
  • 响应时间计算:精确到毫秒级别
  • 状态码检测:记录HTTP响应状态码
  • 超时处理:处理请求超时等异常
  • 日志记录:详细记录所有请求信息
  • 告警机制:响应时间超过阈值自动告警
  • 统计功能:定期统计成功率和平均响应时间
  • 信号处理:优雅处理脚本停止信号

扩展建议

  • 添加邮件告警功能
  • 集成Prometheus/Grafana监控
  • 支持多个API端点监控
  • 添加历史数据存储(数据库)
  • 实现Webhook通知(企业微信、钉钉等)

这个脚本可以作为API健康监控的基础,您可以根据实际需求进行扩展和定制。

抱歉,评论功能暂时关闭!