Skip to content

Feature request: Allow me to set the Logger console property #4901

@webdeveric

Description

@webdeveric

Use case

When running my projects locally, I have lots of log messages and it can be hard to see the message I'm looking for. To fix this, I created styled-json-console, which creates a custom Console object that adds syntax highlighting (ANSI colors) to the JSON output.

In order for me to use my custom Console with Powertools Logger, I have to use Reflect.set() to get around the private access modifier.

Example:

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

const logger = new Logger({
  // Options omitted for brevity
});

if (process.env.IS_OFFLINE === "true") {
  const { createConsole } = await import("styled-json-console");

  const styledConsole = createConsole({
    // Options omitted for brevity
  });

  Reflect.set(logger, "console", styledConsole);
}

This works, but I noticed that when doing this, the console.trace() patch gets undone.

/**
* Patch `console.trace` to avoid printing a stack trace and aligning with AWS Lambda behavior - see #2902
*/
this.console.trace = (message: string, ...optionalParams: unknown[]) => {
this.console.log(message, ...optionalParams);
};

It would be nice if there was an official way to do this instead of using Reflect.set().

Solution/User Experience

Add a devConsole option to Logger and use it in setConsole().

Alternative solutions

Remove `private` from `setConsole()` and add an argument for the `Console` I want to use.

Example:


setConsole(devConsole = console): void {
  this.console = isDevMode() ? devConsole : new Console({
    stdout: process.stdout,
    stderr: process.stderr,
  });

  /**
   * Patch `console.trace` to avoid printing a stack trace and aligning with AWS Lambda behavior - see #2902
   */
  this.console.trace = (message: string, ...optionalParams: unknown[]) => {
    this.console.log(message, ...optionalParams);
  };
}

Acknowledgment

Future readers

Please react with 👍 and your use case to help us understand customer demand.

Metadata

Metadata

Assignees

No one assigned

    Labels

    discussingThe issue needs to be discussed, elaborated, or refinedfeature-requestThis item refers to a feature request for an existing or new utility

    Type

    No type

    Projects

    Status

    Ideas

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions