· aws  · 2 min read

How to use lambda powertools

How to deploy lambda powertools with aws-cdk

How to deploy lambda powertools with aws-cdk

Aws Lambda Powertools

AWS Lambda Powertools is a set of utilities designed to help developers understand exactly what is happening inside their Lambda functions.

How to Install Lambda Powertools in an AWS-CDK Project with TypeScript.

First steps
  • Open your terminal.
  • Make sure you have cdk installed.
  • Create an AWS-CDK project or modify an existing AWS-CDK project to add this new functionality.
  • Install the required packages.
pnpm add @aws-lambda-powertools/logger @aws-lambda-powertools/metrics @aws-lambda-powertools/tracer @middy/core @types/aws-lambda aws-lambda

AWS-CDK Configuration

Configuration for the Powertools.

// ./lib/aws-basic-powertools-stack.ts
const lambdaPowerToolsConfig = {
      LOG_LEVEL: 'DEBUG',
      POWERTOOLS_LOGGER_LOG_EVENT: 'true',
      POWERTOOLS_LOGGER_SAMPLE_RATE: '1',
      POWERTOOLS_TRACE_ENABLED: 'enabled',
      POWERTOOLS_TRACER_CAPTURE_HTTPS_REQUESTS: 'captureHTTPsRequests',
      POWERTOOLS_SERVICE_NAME: 'aws-lambda-service',
      POWERTOOLS_TRACER_CAPTURE_RESPONSE: 'captureResult',
      POWERTOOLS_METRICS_NAMESPACE: 'HandlerMetrics',
    };

Create the lambda function with AWS-CDK.

// ./lib/aws-basic-powertools-stack.ts
const handler = new NodejsFunction(this, 'Handler', {
      entry: join(__dirname, '../functions/index.ts'),
      handler: 'handler',
      runtime: Runtime.NODEJS_20_X,
      logRetention: RetentionDays.ONE_WEEK,
      tracing: Tracing.ACTIVE,
      bundling: {
        minify: true
      },
      depsLockFilePath: join(__dirname, '../package-lock.json'),
      memorySize: 1024,
      timeout: cdk.Duration.seconds(30),
      environment: {
        ...lambdaPowerToolsConfig,
        MY_CUSTOM_VAR: "my-custom-var-value"
      },
    });
    handler.applyRemovalPolicy(cdk.RemovalPolicy.DESTROY);

Create the packages we will use inside the lambda function.

// ./shared/logger.ts
import { Logger } from '@aws-lambda-powertools/logger';
export const logger = new Logger();

Lambda function

Lastly, we will configure and import the required packages inside the Lambda function.

//./functions/index.ts
import { APIGatewayProxyEvent, APIGatewayProxyResult } from 'aws-lambda';
import { MetricUnit, Metrics } from '@aws-lambda-powertools/metrics';
import { logger } from '@shared';
import { Tracer } from '@aws-lambda-powertools/tracer';
import { captureLambdaHandler } from '@aws-lambda-powertools/tracer/middleware';
import { injectLambdaContext } from '@aws-lambda-powertools/logger/middleware';
import { logMetrics } from '@aws-lambda-powertools/metrics/middleware';
import middy from '@middy/core';


const tracer = new Tracer();
const metrics = new Metrics();

export const main = async ({
  body,
}: APIGatewayProxyEvent): Promise<APIGatewayProxyResult> => {
  try {
    if (!body) throw new Error('no payload body');
    logger.info('request', { body })
    logger.debug('debug message', { key: 'value' });
    return {
      statusCode: 200,
      body: JSON.stringify({ success: true, message: "The lambda is alive" }),
    };
  } catch (error: any) {
    logger.error(error.message);

    metrics.addMetric('LambdaError', MetricUnit.Count, 1);
    return {
      statusCode: 500,
      body: JSON.stringify({ success: false, message: error.message }),

    }
  }
};

export const handler = middy(main)
  .use(injectLambdaContext(logger))
  .use(captureLambdaHandler(tracer))
  .use(logMetrics(metrics));

By following this configuration, you should be able to use Lambda Powertools to have better understanding and logs inside your Lambda functions. If you want to see the full code you can visit this repository.

Back to Blog

Related Posts

View All Posts »