Skip to content

Bug: decorated class methods cannot access this in Logger #1058

Closed
@dreamorosi

Description

@dreamorosi

Bug description

A long form description of this issue is available in #1056. This is an issue that affects all three Powertools utilities because they all share similar implementation for the decorators.


When using Powertools in with a Class and when decorating a method, the decorated method does not have access to the correct value of this and so it's not able to call other methods nor read attributes from its same class.

This is due to the fact that the decorator implementation uses an () => () arrow function instead of a regular function () {} one. This mixes the value of this which then causes the wrong value to be passed.

Additionally there's a missing detail in the documentation of the Class instrumentation that prevents compounds the issue described above.

Expected Behavior

Decorated methods have access to the correct value of this and is able to call methods or access attributes/properties.

Current Behavior

See "Steps to Reproduce" section.

Possible Solution

Apply the same changes done to Tracer in #1055

Steps to Reproduce

import {
  LambdaInterface,
  SyncHandler,
  AsyncHandler,
} from "@aws-lambda-powertools/commons";
import { Logger } from "@aws-lambda-powertools/logger";

const logger = new Logger({ serviceName: "serverlessAirline" });

class Lambda implements LambdaInterface {
  greeting: string;

  constructor(message: string) {
    this.greeting = message;
  }

  public getGreeting(): string {
    /* ... */
    return `Hello ${this.greeting}`;
  }

  @logger.injectLambdaContext()
  public handler(_event: any, _context: any, _callback: any): void {
    console.log(this.getGreeting());
  }
}

export const myFunction = new Lambda("World");
export const handler = myFunction.handler.bind(myFunction);

The value logged from console.log(this.getGreeting()); should be Hello World but instead is Hello undefined:
image

Environment

  • Powertools version used: 1.1.0
  • Packaging format (Layers, npm): all
  • AWS Lambda function runtime: all
  • Debugging logs: N/A

Related issues, RFCs

#1056

Metadata

Metadata

Assignees

Labels

bugSomething isn't workingcompletedThis item is complete and has been merged/shippedloggerThis item relates to the Logger Utility

Type

No type

Projects

No projects

Milestone

No milestone

Relationships

None yet

Development

No branches or pull requests

Issue actions