Search code examples
amazon-web-servicesamazon-cloudwatchaws-cloudwatch-log-insights

How to get additional lines of context in a CloudWatch Insights query?


I typically run a query like

fields @timestamp, @message
| filter @message like /ERROR/
| sort @timestamp desc
| limit 20

Is there any way to get additional lines of context around the messages containing "ERROR"? Similar to the A, B, and C flags with grep?

Example

For example, if I have a given log with the following lines

DEBUG Line 1
DEBUG Line 2
ERROR message
DEBUG Line 3
DEBUG Line 4

Currently I get the following result

ERROR message

But I would like to get more context lines like

DEBUG Line 2
ERROR message
DEBUG Line 3

with the option to get more lines of context if I want.


Solution

  • As of 2025, and detailed here, you can now use OpenSearch SQL language with Cloudwatch.

    And by using requestId as suggested in following answer, you can get logs and additional lines of context in one query:

    SELECT b.`timestamp`, b.`requestId`, b.`found`, b.`message`, `@logStream`
    FROM `LogGroupA` a
    LEFT JOIN (
        SELECT `@timestamp` timestamp, `@requestId` requestId, `@message` message, if(`@message` like '%ERROR%', 'Found', '') found
        FROM `LogGroupA`
    ) b ON a.`@requestId` = b.requestId
    WHERE a.`@message` like '%ERROR%'
    ORDER BY b.`requestId`, b.`timestamp`
    

    You will also have logStream link in each lines like suggested in the accepted answer.