首页 > 解决方案 > AWS Cloudwatch Insights - 将字符串解析为 JSON

问题描述

将 JSON 日志发送到 AWS Cloudwatch - 大多数情况下效果很好,但有时,我可能会收到一个不是纯 JSON 的日志条目(或者至少是奇怪的格式)。以下是来自 Slack 机器人的单个日志条目的示例:

{"message": "Unhandled request ({'token': 'ezyBLAHBLAHBLAHDSDFL59', 'team_id': 'TF3BLAHBLAH', 'api_app_id': 'A01EBLAHBLAH', 'event': {'client_msg_id': '5ablahbd-blah-blah-blah-ffe18343blah', 'type': 'message', 'text': 'thanks', 'user': 'UFBLAHBLAH', 'ts': '1605733337.001300', 'team': 'TF3BLAHBLAH', 'blocks': [{'type': 'rich_text', 'block_id': 'gucN', 'elements': [{'type': 'rich_text_section', 'elements': [{'type': 'text', 'text': 'thanks'}]}]}], 'channel': 'D01BLAHBLAH', 'event_ts': '1605733337.001300', 'channel_type': 'im'}, 'type': 'event_callback', 'event_id': 'Ev0BLAHBLAH', 'event_time': 1605733337, 'authorizations': [{'enterprise_id': None, 'team_id': 'TFBLAHBLAH', 'user_id': 'U01BLAHBLAH', 'is_bot': True, 'is_enterprise_install': False}], 'is_ext_shared_channel': False, 'event_context': '1-message-TFBLAHBLAHV-D0BLAHBLAH'})", "level": "WARNING", "name": "slack_bolt.App", "time": "2020-11-18T21:08:18.184+00:00"}

所以它是有效的 JSON,Cloudwatch 正确解析了其中的内容,但未处理请求的大部分细节都被困在一个字符串中:

"message" : "Unhandled request(<lots_of_json>)"
"level": "WARNING"
"name": "slack_bolt.App"
"time": "2020-11-18T21:08:18.184+00:00"

我想摆脱的是那<lots_of_json>部分,我想让它解释为 JSON - 能够报告、排序和聚合这些字段等。

我可以在 Cloudwatch Insights 查询中了解这一点:

fields @timestamp, @message
| filter message like 'Unhandled request'
| parse message 'Unhandled request (*)' as unhandled_payload
| sort @timestamp desc
| limit 20

然后这给了我<lots_of_json>临时字段中的字符串unhandled_payload

现在我怎样才能将unhandled_payloadJSON 格式的字符串解析为 JSON?该parse命令只接受 glob 或正则表达式,并使用其中任何一个来发出这种声音......令人不快。必须有一个命令来解析 JSON 字符串,对吧?它是什么?

(就本问题而言,“去修复应用程序中的日志记录”不是可接受的答案)

标签: amazon-cloudwatchamazon-cloudwatchlogsaws-cloudwatch-log-insights

解决方案


我很想知道解决方案。或者至少 f*** 如何删除日志组中的“web:”前缀以便正确记录 JSON


推荐阅读