Power tools for AWS Lambda

Santhosh Kumar
5 min readApr 22, 2024

--

A developer toolkit to implement Serverless best practices and increase developer velocity

Are you using AWS Lambda? Looking for a toolkit to implement best practices?

Powertools for AWS Lambda is the answer. You can use powertools for aws lambda in both Typescript and Javascript projects, also availabel in other languages such as Python, Java and .NET

In this blog, lets deep dive into Logger.

Key features:

  • Logger with output structured as JSON
  • Capturing key fields from the Lambda context, cold starts
  • Appending additional keys to structured logs
  • Custom log formatter to output logs in a structure compatible to your own choice

Installation:

You can add the library to your project:

npm install @aws-lambda-powertools/logger

Usage:

The Logger utility must always be instantiated out the Lambda Handler. This allows the subsequent invocations processed by the same instance of the hander can reuse the resources. This lets cost saving by reducing the function run time. Logger can keep track of cold start and inject the appropriate fields into the logs.

import { Logger } from '@aws-lambda-powertools/logger';

const logger = new Logger({ serviceName: 'healthCheck' });

export const handler = async (_event, _context): Promise<void> => {
logger.info('This is health check endpoint');
};

The library has three optional settings, these settings on set, would be used across all logs emitted. These settings can be either set via environment variables or passed in the constructor.

  • Service Name: Sets the name of the service of which the lambda function is part of. This will be present across all the log statements of the lambda function.
  • Logging Level: Sets how verbose logger should be.
  • Sample Rate: Probability that a Lambda invocation will print all the log items regardless of the log level settings.

An example to create a logger instance and set values from environment variables.

import { Logger } from '@aws-lambda-powertools/logger';

// Logger parameters fetched from the environment variables
// environment variables are fetched from the YAML file
const logger = new Logger();
logger.info('Hello World');
Resources:
ShoppingCartApiFunction:
Type: AWS::Serverless::Function
Properties:
Runtime: nodejs20.x
Environment:
Variables:
POWERTOOLS_LOG_LEVEL: WARN
POWERTOOLS_SERVICE_NAME: HEALTH_CHECK_SERVICE

An example to create a logger instance and pass the parameters in the constructor.

import { Logger } from '@aws-lambda-powertools/logger';

const logger = new Logger({
logLevel: 'WARN',
serviceName: 'HEALTH_CHECK_SERVICE'
});

Standard structured keys:

Logger will include the following keys as part of the default formatter.

  • level: logging level set for the Lambda function’s invocation.
  • message: A descriptive, human readable representation of log item.
  • sampling_rate: when enabled, it prints all the logs of a percentage of invocations. eg., 10%.
  • service: A unique name identifier of the service which the Lambda function belongs to. Default value is service_undefined
  • timestamp: Timestamp string in simplified extended ISO format.
  • xray_trace_id: X-Ray Trace ID. This value is always presented in Lambda Environment irrespective of tracing enabled or not. Logger will always log this value.
  • error: Optional — An object containing information about the Error passed to the logger.

The default log level is Info. The level can be set using the logLevel constructor option or using the POWERTOOLS_LOG_LEVEL environment variable.Supported log levels and their numeric value are DEBUG8INFO12WARN16ERROR20CRITICAL24SILENT28

An example to work with level,

  • To get the current log level, getLogLevel()method returns the log level such as (DEBUG, INFO, WARN, ERROR, CRITICAL and SILENT)
  • To change the log level , make use of setLogLevel()
  • The logger.level property returns the bumeric value of the current log level

Appending persistent additional log keys and values

You can append additional persistent keys and values in the logs generated during a Lambda invocation.

Add persistent log keys via the constructor method:

example: adding persistent log keys via the constructor

Add persistent logs to an existing Logger instance with the appendKeys method:

example: add persistent log to an existing Logger instance with appendKeys method
Logger will automatically ignore any key with an `undefined` value

Clearing all state

The Logger utility is initialized in the global scope, outside the handler function. When a key value is appended to the persistent log attributes, this data is attached to the Logger instance. Due to Lambda Execution Context reuse, the persistent attributes may be reused across invocations. To make sure that persistent attributes added inside the handler function code are not persisted across invocations, set the parameter clearState as true in the injectLambdaContext middleware or decorator.

In each case, the printed log will look like this:

example: log samples

Logging errors

You can log erros using the warn , info and debug methods. Be aware of the log levels thought, high changes that those erros are missed while analysising the log later depending on the level configuration.

You can also log errors by using the error method and pass the error object as parameter. The error will be logged with default key name as error , however it can be customized with a key name of choice.

--

--

Santhosh Kumar

I am passionate about Transforming ideas into software products and deliver it global.