分组汇总cloudwatch log insights查询

问题描述 投票:0回答:2

我有大约 1 万条来自以下格式的日志洞察日志(由于隐私规则,无法发布实际日志)。我正在使用 boto3 查询日志。

日志洞察查询:

filter @message like /ERROR/

输出日志格式:

 timestamp:ERROR <some details>Apache error....<error details> 
 timestamp:ERROR <some details>Connection error.... <error details> 
 timestamp:ERROR <some details>Database error....<error details>

我需要的是对具有相似子字符串的错误进行分组(如按连接错误、Apache 错误、数据库错误分组)或任何其他类似错误,并得到这些错误的总和。

预期产出:

  Apache error      130
  Database error    2253
  Connection error  3120

是否有一些正则表达式或任何其他方法可以用来提取相似的子字符串并将它们分组并得到总和?无论是在 python 中还是在 log insights 中。

python regex reporting amazon-cloudwatchlogs aws-cloudwatch-log-insights
2个回答
0
投票

在没有看到数据源的情况下是不可能说的,但是您可以使用像这样的日志洞察查询从日志中提取值

filter @logStream like 'SOMEHOST'
| parse @message /<EventID.*?>(?<event_id>\d+)<\/EventID>/
| stats count() by event_id

在这种情况下,我正在解析 Windows 事件日志以计算每种事件类型发生的次数

----------------------
| event_id | count() |
|----------|---------|
| 7036     | 80      |
| 7001     | 4       |
| 7002     | 4       |
| 6013     | 1       |
| 7039     | 1       |
| 7009     | 1       |
| 7000     | 1       |
| 7040     | 2       |
| 7045     | 1       |
----------------------

此查询仅查找事件 ID xml 元素。在您的情况下,您需要查看数据以了解如何最好地识别和提取错误。但如果错误的格式有一个字段,您可以提取它。即使没有字段,如果数据有模式,你仍然可以使用正则表达式


0
投票

如果您将日志放在列表中,则可以使用这样的正则表达式来完成此操作。

logs = [(errors here)]
error_counts = {}

for log in logs:
    match = re.search(r'ERROR\s+(.*?)\s*\.\.\.', log)
    if match:
        error_type = match.group(1)
        error_counts[error_type] = error_counts.get(error_type, 0) + 1

for error_type, count in error_counts.items():
    print(error_type.ljust(20), count)

如果您使用适用于 Python 的 AWS 开发工具包查询日志,则可以使用 filter_pattern 参数按错误类型过滤日志,使用 stats 参数获取每种错误类型的计数,然后使用 start_query 方法提交查询 CloudWatch Logs Insights。

© www.soinside.com 2019 - 2024. All rights reserved.