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

GCP Node.js监控客户端添加内存状态过滤器报错求助

问题解决:GCP Monitoring API获取内存使用率报错修正

错误原因分析

你遇到的报错源于两个核心问题:

  • 混淆了MQL查询语法与listTimeSeries API的filter语法:MQL中的metric.state在API filter里需写成metric.labels.state,必须通过metric.labels前缀访问指标标签
  • 代码filter逻辑错误,重复声明metric.type,错误将"used"当作指标类型,不符合API的过滤规则

另外需要明确:agent.googleapis.com/memory/percent_used指标本身就代表内存已用百分比,无需额外过滤state;若使用agent.googleapis.com/memory/usage(按字节统计内存使用量)这类多状态指标,才需要通过metric.labels.state="used"过滤已用内存数据。

修正后的代码

情况1:获取内存已用百分比(使用percent_used指标)

该指标本身已对应已用占比,无需额外过滤,修正filter即可:

const { MetricServiceClient } = require('@google-cloud/monitoring');

exports.getInstanceRamUtilization = async(instanceid) => {
  const projectId = process.env.PROJECT_ID; 
  const client = new MetricServiceClient();

  try {
    // 获取实例内存使用率指标
    const [timeSeries] = await client.listTimeSeries({
      name: `projects/${projectId}`,
      // 修正过滤规则:移除错误的重复metric.type声明
      filter: `resource.type="gce_instance" AND resource.labels.instance_id="${instanceid}" AND metric.type="agent.googleapis.com/memory/percent_used"`,
      interval: {
        startTime: {
          seconds: Date.now() / 1000 - 60 * 60 * 3, // 获取最近3小时数据
        },
        endTime: {
          seconds: Date.now() / 1000,
        },
      },
    });

    console.log(timeSeries);
    const instanceMetrics = timeSeries.map(series => ({
      metric: series.metric.type,
      values: series.points.map(point => ({
        timestamp: new Date(point.interval.startTime.seconds * 1000),
        value: point.value.doubleValue,
      })),
      current_value: series.points.length ? series.points[0].value.doubleValue : null, // 添加空值判断避免报错
      instance: instanceid,
    }));

    return instanceMetrics;

  } catch (error) {
    console.error('Error retrieving memory of instance:', error);
    throw new Error('Failed to retrieve MEMORY Utilisation');
  }
};

情况2:获取内存已用字节数(使用usage指标,需过滤state)

若需要统计已用内存的具体字节数,使用agent.googleapis.com/memory/usage指标,此时需正确添加标签过滤:

// 仅修改filter部分
filter: `resource.type="gce_instance" AND resource.labels.instance_id="${instanceid}" AND metric.type="agent.googleapis.com/memory/usage" AND metric.labels.state="used"`,

关键注意事项

  • listTimeSeries的filter语法遵循GCP官方定义的规则,核心是通过metric.labels.xxx访问指标标签,与MQL写法不同
  • 不同内存指标的标签结构存在差异,使用前可在GCP控制台的Metrics Explorer中确认指标的标签与类型

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.01 20:30:13