When using serverless framework to build your applications, you depend on the framework's capability to achieve your goals.
One of the main parts of the work process is the ability to debug your code, while you build your logic and in case there are some disruptions in the flow.
When working with AWS Lambda and building your application with SST framework, you can add logs around the logic of your Lambda , but also you need to bare in mind that this constant build up of logs could overwhelm AWS CloudWatch and increase your bills.
While developing there is this amazing Live lambda feature provided by the SST framework which allows you to debug , test and invoke live your AWS Lambda by Postman and whatever endpoint(HTTP, GraphQL) you have chosen.
Once in production and already live, your codebase needs more gentle logging approach. One of the possible solutions is the following:
There are two essentials steps to be completed.
Create custom log method in your code base
Add environment variable to the lambda you are interested to debug
Lets code:
Basically you would have a custom log logic in your codebase, which will be invoked in places.
import { Logger } from '@aws-lambda-powertools/logger';
const logger = new Logger({ serviceName: 'serverless' });
// use logger to create logs at different level
// example:
// logger.info()
// logger.debug()
// logger.error()
function myDebug (message: string, ...args: unknown[]) {
const loggerLevel = logger.getLevelName();
if (loggerLevel === 'DEBUG') {
// log context
logger.debug(message, context: {context: args});
}
}
Then in your Lambda Function snippet you would have environment variable POWERTOOLS_LOG_LEVEL with value INFO.
new Function(stack, "MyFunction", {
handler: "src/lambda.handler",
timeout: 10,
environment: {
POWERTOOLS_LOG_LEVEL: "INFO",
},
});
Like that, whenever you need to debug you would need to change via the AWS Console (no need of deploy) the value of your POWERTOOLS_LOG_LEVEL environmental variable to DEBUG and voila on a so called live
Lambda invocation via SST command sst dev
you would run live your AWS Lambda and have beautiful logs on AWS CloudWatch and your terminal from your code base.
To edit the value of your AWS Lambda's environment variable, choose the Configuration tab, on the Lambda Function page, under Environment variables choose Edit. Once you have changed the value choose Save.
Thank you for reading!
Excited to see any feedback!
Have an amazing journey in cloud world!
Top comments (0)