Intro

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

Key features

  • Capture key fields from Lambda context, cold start and structures logging output as JSON
  • Log Lambda context when instructed (disabled by default)
  • Log sampling prints all logs for a percentage of invocations (disabled by default)
  • Append additional keys to structured log at any point in time

Usage

For more usage examples, see our documentation.

Basic usage

Example

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

// Logger parameters fetched from the environment variables:
const logger = new Logger();

Functions usage with middleware

If you use function-based Lambda handlers you can use the injectLambdaContext() middy middleware to automatically add context to your Lambda logs.

Example

import { Logger } from '@aws-lambda-powertools/logger';
import { injectLambdaContext } from '@aws-lambda-powertools/logger/middleware';
import middy from '@middy/core';

const logger = new Logger();

const lambdaHandler = async (_event: unknown, _context: unknown) => {
logger.info('This is an INFO log with some context');
};

export const handler = middy(lambdaHandler).use(injectLambdaContext(logger));

Object oriented usage with decorators

If instead you use TypeScript classes to wrap your Lambda handler you can use the @logger.injectLambdaContext() decorator.

Example

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

const logger = new Logger();

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);

Functions usage with manual instrumentation

If you prefer to manually instrument your Lambda handler you can use the methods in the Logger class directly.

Example

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

const logger = new Logger();

export const handler = async (_event, context) => {
logger.addContext(context);
logger.info('This is an INFO log with some context');
};

Implements

See

https://docs.powertools.aws.dev/lambda/typescript/latest/core/logger/

Hierarchy (view full)

Implements

  • LoggerInterface

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

  • It adds 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

    Returns void

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

    Parameters

    Returns void

  • Alias for addPersistentLogAttributes.

    Parameters

    Returns void

  • It creates 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

    A new logger instance.

    Example

    // 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;
    }
    }
  • Returns boolean

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

    It 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" | "DEBUG" | "INFO" | "WARN" | "ERROR" | "SILENT"

    The log level name.

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

    Returns boolean

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

    The decorator can be used only when attached to a Lambda function handler which is written as method of a class, and should be declared just before the handler declaration.

    Note: Currently TypeScript only supports decorators on classes and methods. If you are using the function syntax, you should use the middleware instead.

    Parameters

    Returns HandlerMethodDecorator

    Example

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

    const logger = new Logger();

    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);

    See

    https://www.typescriptlang.org/docs/handbook/decorators.html#method-decorators

  • Returns boolean

  • Validate that the service name provided is valid. Used internally during initialization.

    Parameters

    • Optional serviceName: string

      Service name to validate

    Returns boolean

  • Logs a Lambda invocation event, if it should.

    Parameters

    • event: unknown
    • Optional overwriteValue: boolean

    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

  • Alias for removePersistentLogAttributes.

    Parameters

    • keys: string[]

    Returns void

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

    Parameters

    • keys: string[]

    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

  • It sets 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

Generated using TypeDoc