Skip to content

Bug: @metrics.logMetrics and @logger. decorator throws error if code runs outside Lambda #3697

@tavosansal

Description

@tavosansal

Expected Behavior

Tracer module handles the code potentially running outside Lambda context (like locally). When context is needed it can guard that and not let the code error.

Current Behavior

However, the Metrics and Logger module do not.

Specifically the @metrics.logMetrics decorator throws an exception right here because context is undefined.

This is what you get:

TypeError: Cannot read properties of undefined (reading 'functionName')

For Logger, using the @logger.injectLambdaContext also ends up in an error:

TypeError: Cannot read properties of undefined (reading 'invokedFunctionArn')

As a workaround for now I have two blocks in my handler to get around this behavior:

public async handler(event: any, context?: Context): Promise<void> {
    if (context) {
      logger.addContext(context);
    }
   // .... business logic for the handler

  if (context) {
      metrics.publishStoredMetrics();
    }
}

This works but it does not feel as natural as just adding the decorators and letting power tools handle the defaults.

Code snippet

Here is a sample. Just run this code locally:

import { LambdaInterface } from '@aws-lambda-powertools/commons/types';
import { Logger } from '@aws-lambda-powertools/logger';
import { Metrics } from '@aws-lambda-powertools/metrics';

const logger = new Logger({ serviceName: 'Lambda' });
const metrics = new Metrics({ serviceName: 'Lambda', namespace: 'Lambda' });

export class Lambda implements LambdaInterface {
  @logger.injectLambdaContext()
  @metrics.logMetrics()
  public async handler(event: any, context?: any): Promise<void> {
    console.log('You will never get here.');
  }
}

const lambda = new Lambda();
export const handler = lambda.handler.bind(lambda);

(async () => {
  const event = {};
  await handler(event);
})();

Steps to Reproduce

  1. Use the snippet above
  2. Create new file
  3. Run it locally (not in Lambda)
  4. See error

Possible Solution

It would be nice if all modules had a way to guard local development like the Tracer module does.

Powertools for AWS Lambda (TypeScript) version

latest

AWS Lambda function runtime

22.x

Packaging format used

npm

Execution logs

Metadata

Metadata

Assignees

No one assigned

    Labels

    loggerThis item relates to the Logger Utilityneed-responseThis item requires a response from a customer and will considered stale after 2 weeksnot-a-bugNew and existing bug reports incorrectly submitted as bugrejectedThis is something we will not be working on. At least, not in the measurable future

    Type

    No type

    Projects

    Status

    Closed

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions