AWS Lambda அடிப்படையிலான Serverless Observability
விநியோகிக்கப்பட்ட அமைப்புகள் மற்றும் serverless computing உலகில், observability ஐ அடைவது பயன்பாட்டு நம்பகத்தன்மை மற்றும் செயல்திறனை உறுதிசெய்வதற்கான திறவுகோலாகும். இது பாரம்பரிய கண்காணிப்பை விட அதிகமானதை உள்ளடக்குகிறது. Amazon CloudWatch மற்றும் AWS X-Ray போன்ற AWS observability கருவிகளை பயன்படுத்துவதன் மூலம், உங்கள் serverless பயன்பாடுகளில் நுண்ணறிவுகளைப் பெறலாம், சிக்கல்களைத் தீர்க்கலாம், பயன்பாட்டு செயல்திறனை மேம்படுத்தலாம். இந்த வழிகாட்டியில், உங்கள் Lambda அடிப்படையிலான serverless பயன்பாட்டின் Observability ஐ செயல்படுத்த அத்தியாவசிய கருத்துக்கள், கருவிகள் மற்றும் சிறந்த நடைமுறைகளைக் கற்றுக்கொள்வோம்.
உங்கள் உள்கட்டமைப்பு அல்லது பயன்பாட்டிற்கு observability ஐ செயல்படுத்துவதற்கு முன் முதல் படி உங்கள் முக்கிய நோக்கங்களை தீர்மானிப்பதாகும். இது மேம்படுத்தப்பட்ட பயனர் அனுபவம், அதிகரித்த டெவலப்பர் உற்பத்தித்திறன், service level objectives (SLOs) களை சந்திப்பது, வணிக வருவாயை அதிகரிப்பது அல்லது உங்கள் பயன்பாட்டு வகையைப் பொறுத்து வேறு ஏத ேனும் குறிப்பிட்ட நோக்கமாக இருக்கலாம். எனவே, இந்த முக்கிய நோக்கங்களை தெளிவாக வரையறுத்து அவற்றை எவ்வாறு அளவிடுவீர்கள் என்பதை நிறுவுங்கள். பின்னர் அங்கிருந்து backwards work செய்து உங்கள் observability strategy ஐ வடிவமைக்கவும். மேலும் அறிய “Monitor what matters” ஐப் பார்க்கவும்.
Observability இன் தூண்கள்
Observability க்கு மூன்று முக்கிய தூண்கள் உள்ளன:
- Logs: Timestamped records of discrete events that happened within an application or system, such as a failure, an error, or a state transformation
- Metrics: Numeric data measured at various time intervals (time series data); SLIs (request rate, error rate, duration, CPU%, etc.)
- Traces: A trace represents a single user’s journey across multiple applications and systems (usually microservices)
AWS offers both Native and Open source tools to facilitate logging, monitoring metrics, and tracing to obtain actionable insights for your AWS Lambda application.
Logs
In this section of the observability best practices guide, we will deep dive on to following topics:
- Unstructured vs structured logs
- CloudWatch Logs Insights
- Logging correlation Id
- Code Sample using Lambda Powertools
- Log visualization using CloudWatch Dashboards
- CloudWatch Logs Retention
Logs are discrete events that have occurred within your application. These can include events like failures, errors, execution path or something else. Logs can be recorded in unstructured, semi-structured, or structured formats.
Unstructured vs structured logs
We often see developers start with simple log messages within their application using print or console.log statements. These are difficult to parse and analyze programmatically at scale, particularly in a AWS Lambda based applications that can generate many lines of log messages across different log groups. As a result, consolidating these logs in CloudWatch becomes challenging and hard to analyze. You would need to do text match or regular expressions to find relevant information in the logs. Here’s is an example of what unstructured logging looks like:
[2023-07-19T19:59:07Z] INFO Request started
[2023-07-19T19:59:07Z] INFO AccessDenied: Could not access resource
[2023-07-19T19:59:08Z] INFO Request finished
As you can see, the log messages lack a consistent structure, making it challenging to get useful insights from it. Also, it is hard to add contextual information to it.
Whereas structured logging is a way to log information in a consistent format, often in JSON, that allows logs to be treated as data rather than text, which makes querying and filtering simple. It gives developers the ability to efficiently store, retrieve, and analyze the logs programmatically. It also facilitates better debugging. Structured logging provides a simpler way to modify the verbosity of logs across different environments through log levels. Pay attention to logging levels. Logging too much will increase costs and decrease application throughput. Ensure personal identifiable information is redacted before logging. Here’s is an example of what structured logging looks like:
{
"correlationId": "9ac54d82-75e0-4f0d-ae3c-e84ca400b3bd",
"requestId": "58d9c96e-ae9f-43db-a353-c48e7a70bfa8",
"level": "INFO",
"message": "AccessDenied",
"function-name": "demo-observability-function",
"cold-start": true
}
Prefer structured and centralized logging into CloudWatch logs to emit operational information about transactions, correlation identifiers across different components, and business outcomes from your application.
CloudWatch Logs Insights
Use CloudWatch Logs Insights, which can automatically discover fields in JSON formatted logs. In addition, JSON logs can be extended to log custom metadata specific to your application that can be used to search, filter, and aggregate your logs.
Logging correlation Id
For example, for an http request coming in from API Gateway, the correlation Id is set at the requestContext.requestId path, which can be easily extracted and logged in the downstream Lambda functions using Lambda powertools. Distributed systems often involve multiple services and components working together to handle a request. So, logging correlation Id and passing them to downstream systems becomes crucial for end-to-end tracing and debugging. A correlation Id is a unique identifier assigned to a request at the very beginning. As the request moves through different services, the correlation Id is included in the logs, allowing you to trace the entire path of the request. You can either manually insert correlation Id to your AWS Lambda logs or use tools like AWS Lambda powertools to easily grab the correlation Id the from API Gateway and log it along with your application logs. For example, for an http request correlation Id could be a request-id which can be initiated at API Gateway and then passed on to your backend services like Lambda functions.
Code Sample using Lambda Powertools
As a best practice, generate a correlation Id as early as possible in the request lifecycle, preferably at the entry point of your serverless application, such as API Gateway or application load balancer. Use UUIDs, or request id or any other unique attribute which can used to track the request across distributed systems. Pass the correlation id along with each request either as part of the custom header, body or metadata. Ensure that correlation Id is included in all the log entries and traces in your downstream services.
You can either manually capture and include correlation Id as part of your Lambda function logs or use tools like AWS Lambda Powertools. With Lambda Powertools, you can easily grab the correlation Id from predefined request path mapping for supported upstream services and automatically add it alongside your application logs. Also, ensure that correlation Id is added to all your error messages to easily debug and identify the root cause in case of failures and tie it back to the original request.
Let's look at the code sample to demostrate structured logging with correlation id and viewing it in CloudWatch for below serverless architecture:

// Initializing Logger
Logger log = LogManager.getLogger();
// Uses @Logger annotation from Lambda Powertools, which takes optional parameter correlationIdPath to extract correlation Id from the API Gateway header and inserts correlation_id to the Lambda function logs in a structured format.
@Logging(correlationIdPath = "/headers/path-to-correlation-id")
public APIGatewayProxyResponseEvent handleRequest(final APIGatewayProxyRequestEvent input, final Context context) {
...
// The log statement below will also have additional correlation_id
log.info("Success")
...
}
In this example, a Java based Lambda function is using Lambda Powertools library to log correlation_id coming in from the api gateway request.
Sample CloudWatch logs for the code sample:
{
"level": "INFO",
"message": "Success",
"function-name": "demo-observability-function",
"cold-start": true,
"lambda_request_id": "52fdfc07-2182-154f-163f-5f0f9a621d72",
"correlation_id": "<correlation_id_value>"
}_
Log visualization using CloudWatch Dashboards
Once you log the data in structured JSON format, CloudWatch Logs Insights then automatically discovers values in JSON output and parses the messages as fields. CloudWatch Logs insights provides purpose-built SQL-like query language to search and filter multiple log streams. You can perform queries over multiple log groups using glob and regular expressions pattern matching. In addition, you can also write your custom queries and save them to re-run it again without having to re-create them each time.
In CloudWatch logs insights, you can generate visualizations like line charts, bar charts, and stacked area charts from your queries with one or more aggregation functions. You can then easily add these visualization to the CloudWatch Dashboards. Sample dashboard below shows percentile report of Lambda function’s execution duration. Such dashboards will quickly give you insights on where you should focus on improve application performance. Average latency is a good metrics to look at but you should aim to optimize for p99 and not the average latency.
To send (platform, function and extensions) logs to locations other than CloudWatch, you could use Lambda Telemetry API with Lambda Extensions. A number of partner solutions provide Lambda layers which use the Lambda Telemetry API and make integration with their systems easier.
To make the best use of CloudWatch logs insights, think about what data you must be ingesting into your logs in the form of structured logging, which will then help better monitor the health of your application.
CloudWatch Logs Retention
By default all messages that are written to stdout in your Lambda function are saved to an Amazon CloudWatch log stream. Lambda function's execution role should have permission to create CloudWatch log streams and write log events the streams. It is important to be aware that CloudWatch is billed by the amount of data ingested, and the storage used. Therefore, reducing the amount of logging will help you minimize the associated cost. By default CloudWatch logs are kept indefinitely and never expire. It is recommended to configure log retention policy to reduce log-storage costs, and apply it across all your log groups. You might want differing retention policies per environment. Log retention can be configured manually in the AWS console but to ensure consistency and best practices, you should configure it as part of your Infrastructure as Code (IaC) deployments. Below is a sample CloudFormation template that demonstrates how to configuring Log Retention for Lambda function:
Resources:
Function:
Type: AWS::Serverless::Function
Properties:
CodeUri: .
Runtime: python3.8
Handler: main.handler
Tracing: Active
# Explicit log group that refers to the Lambda function
LogGroup:
Type: AWS::Logs::LogGroup
Properties:
LogGroupName: !Sub "/aws/lambda/${Function}"
# Explicit retention time
RetentionInDays: 7
In this example, we created a Lambda function and corresponding log group. The RetentionInDays property is set to 7 days, meaning that logs in this log group will be retained for 7 days before they are automatically deleted, thus helping to control log storage cost.