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

如何解决CloudFormation中JSON日志的MetricFilter模式无效问题?

解决AWS CloudFormation中JSON日志MetricFilter的无效模式问题

你遇到的问题核心是CloudWatch Logs针对JSON格式日志的过滤模式语法,和你之前用的空格分隔日志规则不一样,之前的写法不符合JSON日志的过滤规范,才导致CloudFormation抛出「Invalid metric filter pattern」错误。

先确认下你的目标日志格式:

{ "httpMethod": "GET", "resourcePath": "/deployment", "status": "403", "protocol": "HTTP/1.1", "responseLength": "42" }

问题根源

你之前尝试的两种写法都存在语法问题:

  • "{ $.status = \"403\" }":CloudWatch的JSON过滤模式中,匹配字符串值必须用单引号包裹,双引号会被解析为模式的一部分,直接触发语法错误
  • { $.status = 403 }:CloudFormation要求FilterPattern属性必须是字符串类型,不能直接传入JSON对象

正确的配置写法

把过滤模式里的双引号替换成单引号,同时保持FilterPattern为字符串类型,修改后的完整MetricFilter配置如下:

"DeploymentApiGatewayMetricFilter": {
  "Type": "AWS::Logs::MetricFilter",
  "Properties": {
    "LogGroupName": "/aws/apigateway/DeploymentApiGatewayLogGroup",
    "FilterPattern": "{ $.status = '403' }",
    "MetricTransformations": [
      {
        "MetricValue": "1",
        "MetricNamespace": "ApiGateway",
        "DefaultValue": 0,
        "MetricName": "DeploymentApiGatewayUnauthorized"
      }
    ]
  }
}

额外提示(YAML模板场景)

如果你的CloudFormation模板是YAML格式,写法会更简洁直观,不需要额外转义:

DeploymentApiGatewayMetricFilter:
  Type: AWS::Logs::MetricFilter
  Properties:
    LogGroupName: /aws/apigateway/DeploymentApiGatewayLogGroup
    FilterPattern: '{ $.status = ''403'' }'
    MetricTransformations:
      - MetricValue: '1'
        MetricNamespace: ApiGateway
        DefaultValue: 0
        MetricName: DeploymentApiGatewayUnauthorized

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.11 09:10:37