监控应用响应时间的脚本如何写

wen 实用脚本 1

本文目录导读:

监控应用响应时间的脚本如何写

  1. 使用 curl 的简单脚本
  2. Python 版本(更详细)
  3. 持续监控脚本(带统计)
  4. Docker 环境监控
  5. 使用 Python 的 asyncio 进行异步监控
  6. 使用说明
  7. 高级功能建议

我来为您提供监控应用响应时间的脚本示例,包含多种方案:

使用 curl 的简单脚本

#!/bin/bash
# 监控应用响应时间脚本
URL="https://your-app.com/api/health"
LOG_FILE="/var/log/response_time.log"
# 获取响应时间(毫秒)
response_time=$(curl -o /dev/null -s -w '%{time_total}' $URL)
# 将时间转换为毫秒
response_time_ms=$(echo "$response_time * 1000" | bc)
# 记录日志
echo "$(date '+%Y-%m-%d %H:%M:%S') Response Time: ${response_time_ms}ms" >> $LOG_FILE
# 阈值告警(超过2秒告警)
if (( $(echo "$response_time > 2" | bc -l) )); then
    echo "Warning: Response time too high! ${response_time}s" 
    # 可以添加发送警报的代码
fi

Python 版本(更详细)

#!/usr/bin/env python3
import requests
import time
import logging
from datetime import datetime
# 配置日志
logging.basicConfig(
    filename='response_monitor.log',
    level=logging.INFO,
    format='%(asctime)s - %(message)s'
)
class ResponseMonitor:
    def __init__(self, urls, threshold=2.0):
        self.urls = urls
        self.threshold = threshold  # 阈值(秒)
    def check_response_time(self, url):
        """检查单个URL的响应时间"""
        try:
            start_time = time.time()
            response = requests.get(url, timeout=10)
            end_time = time.time()
            response_time = end_time - start_time
            status_code = response.status_code
            return {
                'url': url,
                'response_time': response_time,
                'status_code': status_code,
                'success': True
            }
        except requests.exceptions.RequestException as e:
            return {
                'url': url,
                'error': str(e),
                'success': False
            }
    def run_checks(self):
        """执行所有URL的检查"""
        results = []
        for url in self.urls:
            result = self.check_response_time(url)
            results.append(result)
            # 记录结果
            if result['success']:
                rt = result['response_time']
                log_msg = f"URL: {url} - Response Time: {rt:.3f}s - Status: {result['status_code']}"
                if rt > self.threshold:
                    logging.warning(f"SLOW RESPONSE - {log_msg}")
                    print(f"[ALERT] {log_msg}")
                else:
                    logging.info(log_msg)
                    print(f"[OK] {log_msg}")
            else:
                logging.error(f"ERROR - URL: {url} - {result['error']}")
                print(f"[ERROR] {url} - {result['error']}")
        return results
# 使用示例
if __name__ == "__main__":
    urls_to_check = [
        "https://api.example.com/health",
        "https://api.example.com/users",
        "https://api.example.com/products"
    ]
    monitor = ResponseMonitor(urls_to_check, threshold=2.0)
    monitor.run_checks()

持续监控脚本(带统计)

#!/bin/bash
# 持续监控脚本
MONITOR_INTERVAL=5  # 监控间隔(秒)
THRESHOLD_MS=2000    # 阈值(毫秒)
URL="https://your-app.com"
LOG_FILE="response_stats.log"
# 统计变量
total_time=0
count=0
max_time=0
min_time=999999
while true; do
    # 获取当前时间
    timestamp=$(date '+%Y-%m-%d %H:%M:%S')
    # 测量响应时间
    start=$(date +%s%N)
    response=$(curl -s -o /dev/null -w "%{http_code}" --connect-timeout 5 --max-time 10 "$URL")
    end=$(date +%s%N)
    # 计算响应时间(毫秒)
    response_time=$(( (end - start) / 1000000 ))
    # 更新统计
    count=$((count + 1))
    total_time=$((total_time + response_time))
    avg_time=$((total_time / count))
    # 更新最大最小值
    if [ $response_time -gt $max_time ]; then
        max_time=$response_time
    fi
    if [ $response_time -lt $min_time ]; then
        min_time=$response_time
    fi
    # 输出结果
    echo "$timestamp | Response: ${response_time}ms | Status: $response | Avg: ${avg_time}ms | Min: ${min_time}ms | Max: ${max_time}ms"
    # 记录到日志文件
    echo "$timestamp,${response_time},$response,${avg_time},${min_time},${max_time}" >> $LOG_FILE
    # 阈值告警
    if [ $response_time -gt $THRESHOLD_MS ]; then
        echo "⚠️ ALERT: Response time exceeded threshold! (${response_time}ms > ${THRESHOLD_MS}ms)"
        # 这里可以添加发送邮件或Slack通知的代码
    fi
    sleep $MONITOR_INTERVAL
done

Docker 环境监控

#!/bin/bash
# Docker容器响应时间监控
CONTAINER_NAME="your-app-container"
DOCKER_URL="http://localhost:8080/health"
while true; do
    # 检查容器是否运行
    if docker ps | grep -q $CONTAINER_NAME; then
        # 测试应用响应时间
        response_time=$(docker exec $CONTAINER_NAME curl -o /dev/null -s -w '%{time_total}' $DOCKER_URL)
        # 检查状态
        if [ $? -eq 0 ]; then
            echo "$(date) - Container: $CONTAINER_NAME - Response Time: ${response_time}s"
            # 检查是否过慢
            if (( $(echo "$response_time > 2" | bc -l) )); then
                echo "Alert: Container response time high!"
            fi
        else
            echo "$(date) - ERROR: Container not responding"
        fi
    else
        echo "$(date) - ERROR: Container $CONTAINER_NAME not running"
    fi
    sleep 5
done

使用 Python 的 asyncio 进行异步监控

#!/usr/bin/env python3
import asyncio
import aiohttp
import time
import logging
from datetime import datetime
async def check_url(session, url, timeout=10):
    """异步检查单个URL"""
    try:
        start_time = time.time()
        async with session.get(url, timeout=timeout) as response:
            response_time = time.time() - start_time
            return {
                'url': url,
                'response_time': response_time,
                'status_code': response.status,
                'success': True
            }
    except Exception as e:
        return {
            'url': url,
            'error': str(e),
            'success': False
        }
async def monitor_urls(urls, interval=10):
    """持续监控多个URL"""
    async with aiohttp.ClientSession() as session:
        while True:
            tasks = [check_url(session, url) for url in urls]
            results = await asyncio.gather(*tasks)
            for result in results:
                if result['success']:
                    rt = result['response_time']
                    print(f"[{datetime.now()}] {result['url']}: {rt:.3f}s")
                    if rt > 2:  # 2秒阈值
                        logging.warning(f"Slow response: {result['url']} - {rt:.3f}s")
                else:
                    print(f"[{datetime.now()}] ERROR: {result['url']} - {result['error']}")
            await asyncio.sleep(interval)
# 使用示例
if __name__ == "__main__":
    urls_to_monitor = [
        "https://api1.example.com/health",
        "https://api2.example.com/health",
        "https://api3.example.com/health"
    ]
    try:
        asyncio.run(monitor_urls(urls_to_monitor, interval=10))
    except KeyboardInterrupt:
        print("监控停止")

使用说明

  1. 基本使用:根据需要选择适合的脚本
  2. 配置:修改URL、阈值、日志路径
  3. 运行
    chmod +x monitor.sh
    ./monitor.sh

高级功能建议

  1. 告警通知:集成邮件、Slack、钉钉等
  2. 数据持久化:存储到数据库
  3. Web界面:使用Flask/Django展示
  4. 分布式监控:支持多节点
  5. 性能分析:详细的时间分解(DNS、连接、传输)

根据您的具体需求,可以选择或修改上述脚本,需要更详细的功能说明吗?

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