首页 > 解决方案 > 在未指定 LogStreamName 的情况下无法获取 CloudWatch 日志

问题描述

我正在使用 Python 3.6 和 boto3==1.7.84。我尝试使用 boto3 从 AWS 获取 CloudWatch 日志,但发现返回的事件数量远少于我在 CloudWatch 洞察页面中看到的数量。我以为

import boto3
client = boto3.client('logs')
response = client.filter_log_events(
    logGroupName='/aws/batch/job',
    startTime=1572520000000,
    endTime=1572570000000,
    filterPattern='exceptions',
)

无论作业流名称如何,都会返回包括“异常”在内的所有事件。然而它什么也没返回。但是如果我像这样指定 logStreamNames

import boto3
client = boto3.client('logs')
response = client.filter_log_events(
    logGroupName='/aws/batch/job',
    logStreamNames=['training/default/[ASpecificID]'],
    startTime=1572520000000,
    endTime=1572570000000,
    filterPattern='exceptions',
)

它确实返回了包含字符串“异常”的日志logStreamNames=['training/default/[ASpecificID]']

另一个奇怪的事情是当我这样做的时候

import boto3
client = boto3.client('logs')
response = client.filter_log_events(
    logGroupName='/aws/batch/job',
    logStreamNamePrefix='training/default',
    startTime=1572520000000,
    endTime=1572570000000,
    filterPattern='exceptions',
)

logStreamNames=['training/default/[ASpecificID]']未返回包含字符串“异常”的日志。确实显示了一些日志logStreamNamePrefix='training/',但不是全部。返回的事件数量比我做的要少得多

fields @timestamp, @message, @logStream
| filter @logStream like /training\/default/
| filter @message like /exceptions/
| limit 10000

CloudWatch 洞察页面中的CloudWatch 日志洞察查询语法。我是否对导致这种差异的 boto3 做错了什么?

标签: python-3.xboto3amazon-cloudwatchlogs

解决方案


从 boto3文档中可以看出。

logStreamNames (list) -- 将结果过滤为仅来自此列表中的日志流的日志。

如果您为 logStreamNamePrefix 和 logStreamNames 指定一个值,则该操作将返回 InvalidParameterException 错误。

logStreamNames 不是必填字段,但它会返回此值的结果,并且只接受列表值。

对于你的奇怪行为logStreamNamePrefix,它最终需要/,但我不确定。

logStreamNamePrefix (string) -- 过滤结果以仅包含来自日志流中名称以该前缀开头的事件。

如果您为 logStreamNamePrefix 和 logStreamNames 指定了一个值,但 logStreamNamePrefix 的值与 logStreamNames 中指定的任何日志流名称都不匹配,则该操作将返回 InvalidParameterException 错误。


推荐阅读