feus4177
feus4177

Reputation: 1393

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.

Upvotes: 76

Views: 26464

Answers (3)

shmuels
shmuels

Reputation: 1393

You can grab the @timestamp from one of the returned lines. Then you can comment out the @message filter and add a range filter based off of that timestamp. Like the following.

fields @timestamp, @message, @logStream
| filter
  #  @message like /ERROR/
  # and 
  @timestamp < 1686761438259 and @timestamp > 1686761418259
| sort @timestamp desc
| limit 20

You can expand and retract the range as you need.

Although more time consuming and not as simple as this it allows you to stay within the Logs Insights query window so you can benefit from the speed and not have to click

load older events

and wait for more records to load.

This is similar to this just it'll work even if you don't have @requestId (which was our case). I imagine this may have been what @SanjoS30 had in mind.

Upvotes: 2

robdasilva
robdasilva

Reputation: 1417

You can actually query the @logStream as well, which in the results will be a link to the exact spot in the respective log stream of the match:

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

That will give you a column similar to the right-most one in this screenshot:

enter image description here

Clicking the link to the right will take you to and highlight the matching log line. I like to open this in a new tab and look around the highlighted line for context.

Upvotes: 91

Kevin
Kevin

Reputation: 1783

I found that the most useful solution is to do your query and search for errors and get the request id from the "requestId" field and open up a second browser tab. In the second tab perform a search on that request id.

Example:

fields @timestamp, @message
| filter @requestId like /fcd09029-0e22-4f57-826e-a64ccb385330/ 
| sort @timestamp asc
| limit 500

With the above query you get all the log messages in the correct order for the request where the error occurred. This is an example that works out of the box with lambda. But if you push logs to CloudWatch in a different way and there is no requestId i would suggest creating a requestId per request or another identifier that is more useful for you use case and push that with your log event.

Upvotes: 21

Related Questions