CloudWatch Logs Insights is the interactive solution for searching and analyzing logs on AWS. It is a powerful analytics tool that allows you to search and query your log data. It provides custom query syntax for debugging and extracting insights from your applications.
CloudWatch Logs Insights is one of the essential parts of any serverless architecture and we will describe its benefits, limitations and pricing in human terms.
Foundations
Some basic features help using CloudWatch Logs Insights to understand your application. Here's a summary:
register event
A log event is a record that contains information sent by your systems.
CloudWatch automatically captures log events from the standard output and standard error streams of your AWS Lambda functions. For example eachconsole.log
in your JavaScript Lambda functions orfmt.Println
in your Golang Lambda function. You can also send log events with the AWS SDKs or CLI usingAPI posts log events.
Each log must have a time stamp and a message.
register flow
A CloudWatch Log Stream is a sequence of log events; log streams are useful for isolating log entries that occurred in the same context. When used with the AWS serverless ecosystem, each AWS Lambda instance receives a unique log stream.
This is ideal for low traffic or development systems, as individual Lambda calls or consecutive calls belong to the same log stream, making it easier to find them quickly. However, log streams can become difficult to manage on high-traffic systems, as successive calls are likely to trigger multiple instances of AWS Lambda, creating multiple log streams and making it difficult to quickly find log files in CloudWatch.
recording group
A CloudWatch Log Group is a collection of log streams; You can define retention policies and access control settings for groups of logs, giving you more control over your infrastructure and ultimately your cloud account.
For AWS Lambda, each Lambda function typically gets a unique log group.
query-syntaxis
CloudWatch Logs Insights uses a custom query language designed to filter and manipulate data in your CloudWatch log pools.
Queries created with this query language are unstructured and can often be assembled, so you can easily reuse snippets of your existing queries or examples found online.
Analysis of log data
The first step in querying logs in CloudWatch Logs Insights is to select the groups of logs to search. CloudWatch Logs Insights supports querying up to 50 log groups in a single query. The query results are also available for 7 days and the query timeout is 60 minutes [bron].
When you ingest data from other AWS services, CloudWatch typically adds discovered fields to the logs for simple queries. For example, when you include logs from AWS Lambda functions, CloudWatch adds fields like@tidsstempel
,@logStream
,@message
,@Order ID
,@duration
,@billedDuration
,@type
,@maxMemoryUsed
,@Memory size
. The complete set of detected fields is describedher.
query-UI
Show data:Campo's
eShow
The first step to extract insights from your logs is usually to select the data to display. There are 2 operators to display data in CloudWatch Logs Insights:Campo's
eShow
.
Show a field:Campo's
Okamp
The command is used to display specific fields in query results.
campos @timestamp, @requestId, @message
The question above shows@tidsstempel
,@Order ID
e@message
on each entry in the register.
OCampo's
The command can be used to create new fields for the query or change field values. In the example below, a new field is createdTotal
would like somenarrate
enumber
and displays it in the query results.
number of errors + number as total
In addition, the fieldTotal
can be used in the rest of the query as if it were part of log events, for example to filter log events based on the value ofTotal
.
To view the results of a query:Show
OShow
command is very similarCampo's
command as it is used to define the fields to display in a query. However, it has several limitations:
- It should only be used once per query, if only the last one
Show
command is used in the query - Cannot be used to create new volatile fields for use elsewhere in the query
Like it isShow
command should normally be used if you don't want to use itCampo's
commando.
Filter data:filter
CloudWatch Logs Insights provides powerful filtering capabilities to find any event usingfilter
commando.
Work with strings
To filter string values, CloudWatch Logs Insights provides the keywordif
and the regular expression operator~=
.
filter message as "exception"
In the example above, we are filtering all log entries truemessage
contains the substringException
.
You can combine multiple filters usinge
eof
keywords and reject specific operations withNee
keyword.
filter message as "Exception" and message other than "Handled" and error ~= /40.*/ or error as /50.*/
A helpful tip to make your searches more readable is to use severalfilter
commands to chain filters insteade
.
filter message as "exception"| filter error ~= /40.*/
Work with numbers
To filter by numbers, CloudWatch Logs Insights provides arithmetic comparison operators:=
,!=
,<
,<=
,>
,>=
that works exactly as you would expect.
filterant > 32
The JSON a strings parser:analyze
Oanalyze
The command is used to extract data from blobs and JSON strings into volatile fields that can be used later in the query (for display, filtering, or calculations...).
Oanalyze
command intuitively matches the JSON string or blob and extracts the data corresponding to the position of*
Character.
Considering this log entry:
Mar 24, 2023 21:09:43,241 [ERROR] {'error': 'ValidationError', 'status': 400} Affected user: 123456
The fragment below fragmentslevel
,exception
eof the user
of the registration file.
parse @message "[*] 'error': '*' Affected user: *" as level , exception , user
As such,level
has the valueWRONG
, is the exceptionvalidation error
eof the user
it is123456
.
Calculate statistics:Statistics
OStatistics
The command allows you to calculate aggregated statistics about login input fields. To use CloudWatch Logs Insights beyond relatively trivial debugging, it's important to become familiar with itStatistics
command. correct use ofStatistics
The command reveals deeper trends and insights into the behavior of your applications.
There are more features available from aggregated features likeaverage
,narrate
,maximum
, ofmin
for non-aggregated features likeearlier
oflast
. A full list of descriptions can be found atdocumentation.
The example below calculates the average duration of AWS Lambda calls based on logs.
filter @type = "REPORT"| average stat (@duration)
The CloudWatch Logs Insights query language provides aspectator
function that allows us to group the results by time period. For example, we can visualize the average duration of Lambda function calls every 5 minutes with the following query.
filter @type = "REPORT"| stats gem(@duration) by bin(5m)
OStatistics
The command can be used to create relatively complex queries.
Classification of results:to organize
Oto organize
The command is used to sort results in ascending or descending order based on a field.
The query below lists AWS Lambda calls with the longest billed duration, with the request ID and billed duration, sorted by billed duration in descending order.
filter @type = "REPORT"| fields @requestId, @billedDuration| sort by @billedDuration desc
Management of the results:limit
Olimit
The command is used to limit the number of rows displayed in the query results. However, it should be noted thatlimit
The command does not reduce the amount of data that CloudWatch Logs Insights scans.
filter @type = "REPORT"| fields @requestId, @billedDuration| sort by @billedDuration desc| limit 10
The above query shows the 10 AWS Lambda calls with the longest billed duration.
query result
Prices in human terms
CloudWatch Logs and Logs Insights have generous free tiers for small applications. They can use and request up to 5 GB of log data each month for free.
When your application exceeds the tier quota, CloudWatch Logs Insights can become expensive.
The following price describes the price ofeu-vest-1
area. Consultofficial documentationdifferent regions.
- $0.50 each GB entry price
- Share price of $0.03 per NL
- $0.005 per GB of scanned data for query
- $0.12 per GB of data scanned to protect and mask sensitive data
price example
Let's say you run a small application exclusively on AWS Lambda. With low traffic, your features are activated 100 times per minute. Each call produces 50 kB of log data. We assume a retention period of 30 days for your log groups:
- Number of subpoenas per month: 100 * 43,800 = 4,380,000 subpoenas
- Total data: 219 GB of log data
- Processing Fee: $109.50
- Price to store 1 month: $6.57
- Cost to mask sensitive data: $26.28
Assuming you don't trade your log data, the cost of CloudWatch logs is $142.35.
However,observability without action is mere storage.
Assuming you run 100 queries per day on your log data, each checking 20 GB of log data:
- Number of requests: 3,000
- Scanned data: 60 TB
- Price for consultation: DKK 300
Total cost: $442.35
Cost optimization
To optimize your CloudWatch Logs and Logs Insights account, you should only keep your data in CloudWatch for as long as the data is critical to the business, then archive it in long-term storage. In addition, it is necessary to limit the amount of data that is scanned during searches.
- Short retention periods: Depending on your compliance requirements, you should allow CloudWatch logs to expire when they are no longer relevant to your activities
- Short search intervals: CloudWatch charges per GB of data scanned when querying. Limiting the time frame of your inquiries will lower your bill
Optimize CloudWatch Insights costs
We don't recommend using less data to lower your CloudWatch bill. It is true that some logs may seem redundant, but this telemetry data is our window into our systems and log pruning can cause blind spots when investigating defects or during incidents.
Conclusion
CloudWatch Logs Insights is often the first step in modern observability for developers working with serverless architectures. It is a powerful solution that helps you understand the inner workings of your apps. However, it has some limitations and the pricing model discourages the use of the logs.
We are working on a better observation solution for serverless architectures:cal basis. It allows you to ask deeper questions about your systems, unify your logs, statistics, traces and all other telemetry data, and the simple pricing model encourages the use of your telemetry data.
Try it, yesOrder.
Next step
- getting togetherRelaxed basisand share what you've built or ask for help.
- Let us know which topics you'd like to see covered next!
FAQs
What is AWS CloudWatch logs insights? ›
CloudWatch Logs Insights enables you to interactively search and analyze your log data in Amazon CloudWatch Logs. You can perform queries to help you more efficiently and effectively respond to operational issues.
How do I trigger Lambda from CloudWatch logs? ›Sign in to the AWS Lambda Console. On the Functions page, select the Lambda function created in Step 2. In the Function overview section, click the + Add trigger button. In the Add Trigger prompt, select CloudWatch Logs from the Select a source dropdown.
How do I extract data from CloudWatch logs? ›- Use subscription filters to stream log data to another receiving source in real time.
- Run a query with CloudWatch Logs Insights.
- Export log data to Amazon Simple Storage Service (Amazon S3) for batch use cases.
- Call GetLogEvents or FilterLogEvents in the CloudWatch API.
- In the navigation pane, choose Log groups.
- For Log Groups, choose the name of the log group containing the log stream to search.
- For Log Streams, choose the name of the log stream to search.
- Under Log events, enter the filter syntax to use.
CloudWatch Logs reports on application logs, while CloudTrail Logs provide you specific information on what occurred in your AWS account. CloudWatch Events is a near real time stream of system events describing changes to your AWS resources. CloudTrail focuses more on AWS API calls made in your AWS account.
What is the purpose of AWS CloudWatch? ›CloudWatch enables you to monitor your complete stack (applications, infrastructure, network, and services) and use alarms, logs, and events data to take automated actions and reduce mean time to resolution (MTTR). This frees up important resources and allows you to focus on building applications and business value.
Does Lambda automatically log to CloudWatch? ›Lambda automatically streams standard output and standard error messages from a Lambda function to CloudWatch Logs, without requiring logging drivers. Lambda also automatically provisions containers that run your Lambda function and configures them to output log messages in separate log streams.
Why is my Lambda function not generating CloudWatch Logs? ›Logs are generated after you run your function for the first time. If there's no log group after invoking the function, it's usually because there's an issue with the function's AWS Identity and Access Management (IAM) permissions.
How do I parse AWS CloudWatch logs? ›- Step 1: Create a Kinesis Data Firehose delivery stream.
- Step 2: Create a destination.
- Step 3: Create a subscription filter.
- Validating the flow of log events.
- Modifying destination membership at runtime.
- In the navigation pane, choose Logs, and then choose Log groups.
- Choose the name of the log group.
- Choose Actions , and then choose Create metric filter.
- For Filter pattern, enter a filter pattern.
How do I automatically export from CloudWatch logs to S3? ›
Open the lambda console, create a lambda function with environment variables and required custom parameter values. Open the eventbridge console, create a rule for target as lambda function to run every 5 min to export the cloudwatch logs to s3 bucket.
How do I check my CloudWatch logs for Lambda? ›- Open the Functions page of the Lambda console.
- Choose a function.
- Choose Monitor.
- Choose View logs in CloudWatch.
- Open the Amazon CloudWatch console.
- In the navigation pane, choose Logs, and then choose Log Insights.
- For Select log group(s), choose one or more log groups to query that consist of AWS WAF access logs.
If your application logs are structured in JSON format, CloudWatch Logs Insights automatically discovers the JSON fields across your log streams in multiple log groups. You can use CloudWatch Logs Insights to analyze your application and system logs, which saves your queries for future use.
How do I search for errors in CloudWatch logs? ›- Set up CloudWatch API access logging using the API Gateway console. ...
- Run the filter-log-events AWS CLI command on the API Gateway access logs using your preferred search utility. ...
- Check the response to your filter-log-events command to identify errors.
CloudTrail Insights identifies behavior that is outside normal patterns, generates Insights events, and delivers those events to a /CloudTrail-Insight folder in the chosen destination S3 bucket for your trail. You can also access and view Insights events in the AWS Management Console for CloudTrail.
How do I write log insights in AWS? ›To run a CloudWatch Logs Insights sample query
Open the CloudWatch console at https://console.aws.amazon.com/cloudwatch/ . In the navigation pane, choose Logs, and then choose Logs Insights. On the Logs Insights page, the query editor contains a default query that returns the 20 most recent log events.
- In the navigation pane, choose Logs, and then choose Logs Insights.
- On the right, choose Queries.
- Select your query from Saved queries list. It appears in the query editor.
- Choose Run.
The two services, Amazon CloudWatch and CloudTrail can be used together. CloudWatch focuses on the activity of AWS services and resources, reporting on their health and performance. On the other hand, CloudTrail is a log of all actions that have taken place inside your AWS environment.