如何定义 AWS MetricFilter FilterPattern 以匹配 CloudWatch 中的 JSON 格式的日志事件?

use*_*985 2 amazon-web-services aws-cloudformation amazon-cloudwatchlogs amazon-cloudwatch-metrics

我正在尝试在 AWS CloudFormation 模板中定义一个指标筛选器,以匹配来自 CloudWatch 的 JSON 格式的日志事件。以下是日志事件的示例:

{
    "httpMethod": "GET",
    "resourcePath": "/deployment",
    "status": "403",
    "protocol": "HTTP/1.1",
    "responseLength": "42"
}
Run Code Online (Sandbox Code Playgroud)

这是我目前使用文档中给出的示例创建 MetricFilter 以匹配状态字段的尝试:FilterAndPatternSyntax

"DeploymentApiGatewayMetricFilter": {
  "Type": "AWS::Logs::MetricFilter",
  "Properties": {
    "LogGroupName": "/aws/apigateway/DeploymentApiGatewayLogGroup",
    "FilterPattern": "{ $.status = \"403\" }",
    "MetricTransformations": [
      {
        "MetricValue": "1",
        "MetricNamespace": "ApiGateway",
        "DefaultValue": 0,
        "MetricName": "DeploymentApiGatewayUnauthorized"
      }
    ]
  }
}
Run Code Online (Sandbox Code Playgroud)

我在 CloudFormation 中收到“无效的指标过滤器模式”消息。

我尝试过的其他变体不起作用:

"{ $.status = 403 }" <- no escaped characters
{ $.status = 403 } <- using a json object instead of string
Run Code Online (Sandbox Code Playgroud)

我已经能够使用以类似方式定义的括号表示法成功过滤以空格分隔的日志事件,但 json 格式的日志事件不遵循相同的约定。

小智 6

遇到了同样的问题,并且能够通过使用 aws-cdk 编写几行来生成过滤器模式模板以查看它与我所拥有的之间的区别。

似乎它需要用括号括起来的每条标准。

- FilterPattern: '{ $.priority = "ERROR" && $.message != "*SomeMessagePattern*" }'
+ FilterPattern: '{ ($.priority = "ERROR") && ($.message != "*SomeMessagePattern*") }'
Run Code Online (Sandbox Code Playgroud)

不幸的是,CloudFormation 中 MetricFilter 的 AWS 文档没有 JSON 模式示例。