You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何将Cypress实例的CPU/内存使用数据上报至外部API?

记录Cypress实例的CPU/内存占用并发送到外部API

可以通过捕获Cypress的DEBUG输出、解析数据后发送到外部API的方式实现,以下是两种实用方案:

方法一:使用Shell脚本(适合Linux/macOS服务器)

编写脚本捕获Cypress的进程分析日志,提取CPU和内存数据后通过curl发送到API:

#!/bin/bash

# 配置项:替换为你的服务器标识和API地址
SERVER_ID="server-01"
API_URL="https://your-external-api-endpoint.com/resource-usage"

# 运行Cypress并捕获DEBUG日志,过滤进程分析器相关输出
DEBUG=cypress:server:util:process_profiler cypress run 2>&1 | while read -r line; do
    # 可选:打印原始日志用于调试
    echo "$line"
    
    # 检查是否为进程分析器日志行
    if [[ "$line" == *"cypress:server:util:process_profiler"* ]]; then
        # 提取CPU百分比和内存使用量(根据实际日志格式调整正则)
        CPU_PERCENT=$(echo "$line" | grep -oP 'cpuPercent: \K[\d.]+')
        MEMORY_USAGE=$(echo "$line" | grep -oP 'memoryUsage: \K\d+')
        
        # 确保提取到有效数据后发送请求
        if [[ -n "$CPU_PERCENT" && -n "$MEMORY_USAGE" ]]; then
            curl -s -X POST "$API_URL" \
                -H "Content-Type: application/json" \
                -d '{
                    "server_id": "'"$SERVER_ID"'",
                    "cpu_percent": '"$CPU_PERCENT"',
                    "memory_usage": '"$MEMORY_USAGE"',
                    "timestamp": "'$(date -u +"%Y-%m-%dT%H:%M:%SZ")'"
                }'
        fi
    fi
done

使用说明:

  • 替换SERVER_ID为当前服务器的唯一标识(如主机名、IP)
  • 替换API_URL为你的外部API端点
  • 给脚本添加执行权限:chmod +x cypress-resource-logger.sh
  • 运行脚本:./cypress-resource-logger.sh

方法二:使用Node.js脚本(更灵活的解析逻辑)

如果需要复杂解析或批量发送,Node.js脚本是更好的选择:

const { spawn } = require('child_process');
const axios = require('axios');

// 配置项
const config = {
  serverId: 'server-01',
  apiUrl: 'https://your-external-api-endpoint.com/resource-usage',
  batchSize: 5, // 批量发送数据的条数
  batchTimeout: 1000 // 批量发送的超时时间(毫秒)
};

let dataBatch = [];
let batchTimer = null;

// 启动Cypress进程
const cypressProcess = spawn('cypress', ['run'], {
  env: { ...process.env, DEBUG: 'cypress:server:util:process_profiler' }
});

// 处理标准输出和错误输出
['stdout', 'stderr'].forEach(stream => {
  cypressProcess[stream].on('data', handleOutput);
});

function handleOutput(data) {
  const lines = data.toString().trim().split('\n');
  lines.forEach(processLogLine);
}

function processLogLine(line) {
  if (!line.includes('cypress:server:util:process_profiler')) return;

  try {
    // 提取日志中的JSON数据块
    const jsonMatch = line.match(/\{[^}]+\}/);
    if (!jsonMatch) return;

    const usageData = JSON.parse(jsonMatch[0]);
    const record = {
      server_id: config.serverId,
      cpu_percent: usageData.cpuPercent,
      memory_usage: usageData.memoryUsage,
      timestamp: new Date().toISOString()
    };

    // 加入批量队列
    dataBatch.push(record);
    triggerBatchSend();
  } catch (err) {
    console.error('解析日志失败:', line, err.message);
  }
}

function triggerBatchSend() {
  // 清除现有定时器,避免重复触发
  if (batchTimer) clearTimeout(batchTimer);

  // 达到批量条数或超时后发送
  if (dataBatch.length >= config.batchSize) {
    sendBatch();
  } else {
    batchTimer = setTimeout(sendBatch, config.batchTimeout);
  }
}

async function sendBatch() {
  if (dataBatch.length === 0) return;

  const batch = [...dataBatch];
  dataBatch = [];

  try {
    await axios.post(config.apiUrl, batch);
    console.log(`成功发送 ${batch.length} 条资源记录`);
  } catch (err) {
    console.error('发送数据到API失败:', err.message);
    // 可选:将失败的批次重新加入队列
    dataBatch = [...batch, ...dataBatch];
  }
}

// 处理Cypress进程退出
cypressProcess.on('close', (code) => {
  console.log(`Cypress测试结束,退出码: ${code}`);
  // 发送剩余的批量数据
  sendBatch();
});

使用说明:

  • 安装依赖:npm install axios
  • 修改config中的服务器标识和API地址
  • 运行脚本:node cypress-resource-logger.js

注意事项

  • 日志格式适配:Cypress的process_profiler输出格式可能随版本变化,需根据实际输出调整解析逻辑
  • API频率控制:若Cypress输出频率过高,建议使用批量发送避免触发API限流
  • 错误处理:添加日志记录或重试机制,防止因API临时故障丢失数据
  • 服务器标识:每个服务器使用唯一ID,方便API端区分不同测试节点的资源数据

内容的提问来源于stack exchange,提问作者Rahul

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.17 13:55:16