如何使用JSON度量标准筛选器从Lambda筛选CloudWatch日志

时间:2017-10-21 20:10:08

标签: json aws-lambda amazon-cloudwatch amazon-cloudwatch-metrics

直接使用documentation中的示例,在lambda函数中我放了:

console.log(
        {
          "eventType": "UpdateTrail",
          "sourceIPAddress": "111.111.111.111",
          "arrayKey": [
                "value",
                "another value"
          ],
          "objectList": [
               {
                 "name": "a",
                 "id": 1
               },
               {
                 "name": "b",
                 "id": 2
               }
          ],
          "SomeObject": null,
          "ThisFlag": true
        }) 

然后,我在CloudWatch中创建一个日志指标过滤器,其中包含文档示例中指定的过滤器模式:

{ $.eventType = "UpdateTrail" }

过滤器不会像文档中所说的那样生成度量标准 - 这是输出:

2017-10-23T13:27:19.320Z    1143e2b0-eea6-4225-88c0-efcd79055f7b    { eventType: 'UpdateTrail',
sourceIPAddress: '111.111.111.111',
arrayKey: [ 'value', 'another value' ],
objectList: [ { name: 'a', id: 1 }, { name: 'b', id: 2 } ],
SomeObject: null,
ThisFlag: true }

因此,您可以看到时间戳和标识符前置于JSON。

Amazon Cloudwatch log filtering - JSON syntax中的答案说,这是因为Lambda将日志转换为字符串。 How to parse mixed text and JSON log entries in AWS CloudWatch for Log Metric Filter大致相同。在任何一种情况下都不提供解决方案。如何使用JSON Metric过滤器从Lambda过滤CloudWatch日志?

1 个答案:

答案 0 :(得分:3)

查看日志行的实际情况。如果你看到这样的东西,它就不是一个有效的json:

{ eventType: 'UpdateTrail', ... }

你想要的是这样的(注意引用):

{ "eventType": "UpdateTrail", ...}

为此,请尝试将对象包装在JSON.stringify()中,如下所示:

console.log(
        JSON.stringify(
            {
              "eventType": "UpdateTrail",
              "sourceIPAddress": "111.111.111.111",
              "arrayKey": [
                    "value",
                    "another value"
              ],
              "objectList": [
                   {
                     "name": "a",
                     "id": 1
                   },
                   {
                     "name": "b",
                     "id": 2
                   }
              ],
              "SomeObject": null,
              "ThisFlag": true
            }
        )
    ) 
相关问题