The Logger utility provides an opinionated logger with output structured as JSON for AWS Lambda.

Key features

  • Capture key fields from AWS Lambda context, cold start, and structure log output as JSON
  • Append additional keys to one or all log items
  • Switch log level to DEBUG based on a sample rate value for a percentage of invocations

After initializing the Logger class, you can use the methods to log messages at different levels.

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

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

export const handler = async (event, context) => {
logger.info('This is an INFO log');
logger.warn('This is a WARNING log');
};

To enrich the log items with information from the Lambda context, you can use the addContext() method.

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

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

export const handler = async (event, context) => {
logger.addContext(context);

logger.info('This is an INFO log with some context');
};

You can also add additional attributes to all log items using the appendKeys() method.

export const handler = async (event, context) => {
logger.appendKeys({ key1: 'value1' });

logger.info('This is an INFO log with additional keys');

logger.removeKeys(['key1']);
};

If you write your functions as classes and use TypeScript, you can use the Logger.injectLambdaContext class method decorator to automatically add context to your logs and clear the state after the invocation.

If instead you use Middy.js middlewares, you use the injectLambdaContext() middleware.

Hierarchy (View Summary)

Implements

Constructors

Accessors

  • get level(): number
  • Log level used by the current instance of Logger.

    Returns the log level as a number. The higher the number, the less verbose the logs. To get the log level name, use the () method.

    Returns number

Methods

  • Add the current Lambda function's invocation context data to the powertoolLogData property of the instance. This context data will be part of all printed log items.

    Parameters

    • context: Context

      The Lambda function's invocation context.

    Returns void

  • Add the given persistent attributes (key-value pairs) to all log items generated by this Logger instance.

    Parameters

    • attributes: LogAttributes

      The attributes to add to all log items.

    Returns void

    This method is deprecated and will be removed in the future major versions, please use () instead.

  • Add the given temporary attributes (key-value pairs) to all log items generated by this Logger instance.

    Parameters

    • attributes: LogAttributes

      The attributes to add to all log items.

    Returns void

  • Add the given persistent attributes (key-value pairs) to all log items generated by this Logger instance.

    Parameters

    • attributes: LogAttributes

      The attributes to add to all log items.

    Returns void

  • Create a log item and populate it with the given log level, input, and extra input.

    We start with creating an object with base attributes managed by Powertools. Then we create a second object with persistent attributes provided by customers either directly to the log entry or through initial configuration and appendKeys method.

    Once we have the two objects, we pass them to the formatter that will apply the desired formatting to the log item.

    Parameters

    • logLevel: number

      The log level of the log item to be printed

    • input: LogItemMessage

      The main input of the log item, this can be a string or an object with additional attributes

    • extraInput: LogItemExtraInput

      Additional attributes to be added to the log item

    Returns LogItem

  • Create a separate Logger instance, identical to the current one. It's possible to overwrite the new instance options by passing them.

    Parameters

    Returns Logger

  • Factory method for instantiating logger instances. Used by createChild method. Important for customization and subclassing. It allows subclasses, like MyOwnLogger, to override its behavior while keeping the main business logic in createChild intact.

    Parameters

    Returns Logger

    // MyOwnLogger subclass
    class MyOwnLogger extends Logger {
    protected createLogger(options?: ConstructorOptions): MyOwnLogger {
    return new MyOwnLogger(options);
    }
    // No need to re-implement business logic from `createChild` and keep track on changes
    public createChild(options?: ConstructorOptions): MyOwnLogger {
    return super.createChild(options) as MyOwnLogger;
    }
    }
  • Get the cold start status of the current execution environment.

    Returns boolean

    import { Utility } from '@aws-lambda-powertools/commons';

    const utility = new Utility();
    utility.isColdStart(); // true
    utility.isColdStart(); // false

    The method also flips the cold start status to false after the first invocation.

  • Get the default service name.

    Returns string

  • A custom JSON replacer function that is used to serialize the log items.

    By default, we already extend the default serialization behavior to handle BigInt and Error objects, as well as remove circular references. When a custom JSON replacer function is passed to the Logger constructor, it will be called before our custom rules for each key-value pair in the object being stringified.

    This allows you to customize the serialization while still benefiting from the default behavior.

    Returns (key: string, value: unknown) => void

  • Get the log level name of the current instance of Logger.

    Returns the log level name, i.e. INFO, DEBUG, etc. To get the log level as a number, use the Logger.level property.

    Returns "CRITICAL" | "TRACE" | "DEBUG" | "INFO" | "WARN" | "ERROR" | "SILENT"

  • Return a boolean value. True means that the Lambda invocation events are printed in the logs.

    Returns boolean

  • Return the persistent log attributes, which are the attributes that will be logged in all log items.

    Returns LogAttributes

  • Class method decorator that adds the current Lambda function context as extra information in all log items.

    This decorator is useful when you want to add the Lambda context to all log items and it works only when decorating a class method that is a Lambda function handler.

    Parameters

    Returns HandlerMethodDecorator

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

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

    class Lambda implements LambdaInterface {
    // Decorate your handler class method
    ⁣@logger.injectLambdaContext()
    public async handler(_event: unknown, _context: unknown): Promise<void> {
    logger.info('This is an INFO log with some context');
    }
    }

    const handlerClass = new Lambda();
    export const handler = handlerClass.handler.bind(handlerClass);
  • Get the cold start status of the current execution environment.

    Returns boolean

    import { Utility } from '@aws-lambda-powertools/commons';

    const utility = new Utility();
    utility.isColdStart(); // true
    utility.isColdStart(); // false
  • Validate that the service name provided is valid. Used internally during initialization.

    Parameters

    • OptionalserviceName: string

      Service name to validate

    Returns boolean

  • Log the AWS Lambda event payload for the current invocation if the environment variable POWERTOOLS_LOGGER_LOG_EVENT is set to true.

    Parameters

    • event: unknown

      The AWS Lambda event payload.

    • OptionaloverwriteValue: boolean

      Overwrite the environment variable value.

    Returns void

    process.env.POWERTOOLS_LOGGER_LOG_EVENT = 'true';

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

    const logger = new Logger();

    export const handler = async (event) => {
    logger.logEventIfEnabled(event);
    // ... your handler code
    }
  • Print a given log with given log level.

    Parameters

    • logLevel: number

      The log level

    • log: LogItem

      The log item to print

    Returns void

  • This method allows recalculating the initial sampling decision for changing the log level to DEBUG based on a sample rate value used during initialization, potentially yielding a different outcome.

    Returns void

  • Remove temporary attributes based on provided keys to all log items generated by this Logger instance.

    Parameters

    • keys: string[]

      The keys to remove.

    Returns void

  • Remove the given keys from the persistent keys.

    Parameters

    • keys: string[]

      The keys to remove from the persistent attributes.

    Returns void

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

    const logger = new Logger({
    persistentKeys: {
    environment: 'prod',
    },
    });

    logger.removePersistentKeys(['environment']);
  • Parameters

    • keys: string[]

      The keys to remove.

    Returns void

    This method is deprecated and will be removed in the future major versions. Use () instead.

  • Remove all temporary log attributes added with appendKeys() method.

    Returns void

  • Set the log level for this Logger instance.

    If the log level is set using AWS Lambda Advanced Logging Controls, it sets it instead of the given log level to avoid data loss.

    Parameters

    • logLevel: LogLevel

      The log level to set, i.e. error, warn, info, debug, etc.

    Returns void

  • Set the given attributes (key-value pairs) to all log items generated by this Logger instance. Note: this replaces the pre-existing value.

    Parameters

    Returns void

    This method is deprecated and will be removed in the future major versions, please use () instead.

  • Check whether the current Lambda invocation event should be printed in the logs or not.

    Parameters

    • OptionaloverwriteValue: boolean

      Overwrite the environment variable value.

    Returns boolean