【问题标题】:How do I define an AWS MetricFilter FilterPattern to match a JSON-formatted log event in CloudWatch?如何定义 AWS MetricFilter FilterPattern 以匹配 CloudWatch 中 JSON 格式的日志事件?
【发布时间】:2021-08-26 01:25:53
【问题描述】:

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

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

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

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

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

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

"{ $.status = 403 }" <- no escaped characters
{ $.status = 403 } <- using a json object instead of string

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

【问题讨论】:

    标签: amazon-web-services amazon-cloudformation amazon-cloudwatchlogs amazon-cloudwatch-metrics


    【解决方案1】:

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

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

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

    很遗憾,CloudFormation 中的 MetricFilter 的 AWS 文档没有 JSON 模式的示例。

    【讨论】:

      【解决方案2】:

      我也一直遇到这个错误,因为我的度量过滤器在外面用双引号格式化。

            FilterPattern: "{ ($.errorCode = '*UnauthorizedOperation') || ($.errorCode = 'AccessDenied*') }"
      

      The docs say:

      完全由字母数字字符组成的字符串不需要加引号。包含 unicode 和其他字符(例如,'@、''$、'',' 等)的字符串必须用双引号括起来才有效。

      它没有明确列出 splat/wildcard * 字符,所以我认为在单引号内可以,但它一直说度量过滤器模式不好,因为单引号中的 *

      我本可以在模式外部使用单引号,在内部字符串周围使用双引号,但我选择像这样转义双引号。

            FilterPattern: "{ ($.errorCode = \"*UnauthorizedOperation\") || ($.errorCode = \"AccessDenied*\") }"
      

      【讨论】:

        猜你喜欢
        • 2021-05-16
        • 1970-01-01
        • 2021-12-24
        • 2020-10-06
        • 1970-01-01
        • 2020-06-14
        • 2020-09-20
        • 2021-06-01
        • 2018-06-07
        相关资源
        最近更新 更多