or run

npx @tessl/cli init
Log in

Version

Tile

Overview

Evals

Files

docs

advanced-patterns.mdapi-reference.mdindex.mdintegration.md
tile.json

api-reference.mddocs/

API Reference

Complete API documentation for @aws-lambda-powertools/logger.

Logger Class

Constructor

constructor(options?: ConstructorOptions);

Options:

  • logLevel?: LogLevel - Threshold for log output (default: 'INFO')
  • serviceName?: string - Service identifier in logs
  • sampleRateValue?: number - 0-1 sampling rate for DEBUG logs
  • persistentKeys?: LogAttributes - Attributes in all logs across invocations
  • environment?: string - Environment name
  • logFormatter?: LogFormatter - Custom log formatter
  • logRecordOrder?: string[] - Key ordering (mutually exclusive with logFormatter)
  • jsonReplacerFn?: CustomJsonReplacerFn - Custom JSON serialization
  • logBufferOptions?: LogBufferOptions - Buffer configuration
  • correlationIdSearchFn?: (event: unknown) => string - Custom correlation ID extraction

Examples:

const logger = new Logger();
const logger = new Logger({ serviceName: 'orderService' });
const logger = new Logger({
  serviceName: 'orderService',
  logLevel: 'DEBUG',
  persistentKeys: { version: '1.0.0' }
});

Logging Methods

trace(input: LogItemMessage, ...extraInput: LogItemExtraInput): void;
debug(input: LogItemMessage, ...extraInput: LogItemExtraInput): void;
info(input: LogItemMessage, ...extraInput: LogItemExtraInput): void;
warn(input: LogItemMessage, ...extraInput: LogItemExtraInput): void;
error(input: LogItemMessage, ...extraInput: LogItemExtraInput): void;
critical(input: LogItemMessage, ...extraInput: LogItemExtraInput): void;

Parameters:

  • input - String message OR object with message property
  • extraInput - Error, string, or multiple attribute objects

Examples:

logger.info('Message');
logger.info('Message', { userId: '123' });
logger.error('Failed', error as Error);
logger.error('Failed', { customError: error as Error, orderId: '123' });
logger.info({ message: 'Created', orderId: '123', amount: 99.99 });

Context Management

addContext(context: Context): void;

Adds Lambda execution context to all subsequent logs.

Adds:

  • function_name, function_arn, function_memory_size
  • function_request_id, cold_start, xray_trace_id

Example:

export const handler = async (event, context) => {
  logger.addContext(context);
  logger.info('Processing'); // Includes Lambda context
};

Temporary Attribute Management

appendKeys(attributes: LogAttributes): void;
removeKeys(keys: string[]): void;
resetKeys(): void;

Temporary attributes persist only during current invocation (until manually removed or resetKeys called).

Examples:

logger.appendKeys({ requestId: '123', userId: '456' });
logger.removeKeys(['requestId']);
logger.resetKeys(); // Clear all temporary keys

Persistent Attribute Management

appendPersistentKeys(attributes: LogAttributes): void;
removePersistentKeys(keys: string[]): void;
getPersistentLogAttributes(): LogAttributes;

Persistent attributes remain across all invocations.

Examples:

logger.appendPersistentKeys({ version: '2.0.0', region: 'us-east-1' });
logger.removePersistentKeys(['version']);
const attrs = logger.getPersistentLogAttributes();

Log Level Management

setLogLevel(logLevel: LogLevel): void;
getLevelName(): Uppercase<LogLevel>;
get level(): number;

Examples:

logger.setLogLevel('DEBUG');
const name = logger.getLevelName(); // 'DEBUG'
const level = logger.level; // 8

Log Level Thresholds:

  • TRACE: 6
  • DEBUG: 8
  • INFO: 12 (default)
  • WARN: 16
  • ERROR: 20
  • CRITICAL: 24
  • SILENT: 28

Correlation ID Management

setCorrelationId(value: unknown, correlationIdPath?: string): void;
getCorrelationId(): unknown;

Parameters:

  • value - Correlation ID value or event object
  • correlationIdPath - Optional JMESPath expression to extract from event

Examples:

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

logger.setCorrelationId(event, correlationPaths.API_GATEWAY_REST);
const id = logger.getCorrelationId();

Log Buffering

flushBuffer(): void;
clearBuffer(): void;

Examples:

try {
  await process();
  logger.clearBuffer(); // Discard buffered logs
} catch (error) {
  logger.flushBuffer(); // Output buffered logs for debugging
  logger.error('Failed', error as Error);
}

Event Logging

logEventIfEnabled(event: unknown, overwriteValue?: boolean): void;
getLogEvent(): boolean;
shouldLogEvent(overwriteValue?: boolean): boolean;

Examples:

logger.logEventIfEnabled(event);
logger.logEventIfEnabled(event, true); // Force log

if (logger.getLogEvent()) {
  // Event logging is enabled
}

Debug Sampling

refreshSampleRateCalculation(): void;

Recalculate debug sampling for warm Lambda starts.

Example:

export const handler = async (event, context) => {
  logger.refreshSampleRateCalculation(); // Fresh calculation each invocation
  logger.debug('Sampled'); // Logged based on sampleRateValue
};

Child Logger Creation

createChild(options?: ConstructorOptions): Logger;

Creates child logger inheriting parent configuration.

Example:

const parent = new Logger({
  serviceName: 'parent',
  persistentKeys: { version: '1.0.0' }
});

const child = parent.createChild({
  serviceName: 'child',
  persistentKeys: { component: 'processor' }
});

child.info('Log'); // Includes both parent and child keys

Decorator

injectLambdaContext(options?: InjectLambdaContextOptions): HandlerMethodDecorator;

TypeScript decorator for automatic Lambda context injection.

Options:

  • logEvent?: boolean - Log event payload (default: false)
  • resetKeys?: boolean - Clear temporary keys after invocation (default: false)
  • flushBufferOnUncaughtError?: boolean - Flush buffer on errors (default: false)
  • correlationIdPath?: string - JMESPath for correlation ID

Example:

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

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

class Lambda implements LambdaInterface {
  @logger.injectLambdaContext({ resetKeys: true })
  public async handler(event: unknown, context: Context): Promise<void> {
    logger.info('Processing'); // Context auto-injected
  }
}

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

Middy Middleware

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

function injectLambdaContext(
  target: Logger | Logger[],
  options?: InjectLambdaContextOptions
): MiddlewareLikeObj;

Parameters:

  • target - Logger instance or array of loggers
  • options - Same as decorator options

Behavior:

  • Before: Adds Lambda context, logs event (if enabled), sets correlation ID
  • After: Resets temporary keys (if enabled)
  • OnError: Flushes buffer (if enabled), resets keys (if enabled)

Examples:

import middy from '@middy/core';

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

const lambdaHandler = async (event, context) => {
  logger.info('Processing');
  return { statusCode: 200 };
};

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

// Multiple loggers
const mainLogger = new Logger({ serviceName: 'main' });
const auditLogger = new Logger({ serviceName: 'audit' });
export const handler = middy(lambdaHandler).use(
  injectLambdaContext([mainLogger, auditLogger], { resetKeys: true })
);

// Full options
export const handler = middy(lambdaHandler).use(
  injectLambdaContext(logger, {
    logEvent: false,
    resetKeys: true,
    flushBufferOnUncaughtError: true,
    correlationIdPath: correlationPaths.API_GATEWAY_REST
  })
);

Correlation ID Utilities

import { correlationPaths, search } from '@aws-lambda-powertools/logger/correlationId';

const correlationPaths: {
  API_GATEWAY_REST: string;
  API_GATEWAY_HTTP: string;
  APPSYNC_RESOLVER: string;
  APPSYNC_AUTHORIZER: string;
  APPLICATION_LOAD_BALANCER: string;
  EVENT_BRIDGE: string;
  LAMBDA_FUNCTION_URL: string;
  S3_OBJECT_LAMBDA: string;
  VPC_LATTICE: string;
};

function search(expression: string, data: unknown): unknown;

Correlation Paths:

  • API_GATEWAY_REST: 'requestContext.requestId'
  • API_GATEWAY_HTTP: 'requestContext.requestId'
  • APPSYNC_RESOLVER: 'request.headers."x-amzn-trace-id"'
  • APPSYNC_AUTHORIZER: 'requestContext.requestId'
  • APPLICATION_LOAD_BALANCER: 'headers."x-amzn-trace-id"'
  • EVENT_BRIDGE: 'id'
  • LAMBDA_FUNCTION_URL: 'requestContext.requestId'
  • S3_OBJECT_LAMBDA: 'xAmzRequestId'
  • VPC_LATTICE: 'headers."x-amzn-trace-id"'

Search Function:

Requires @aws-lambda-powertools/jmespath peer dependency.

const requestId = search(correlationPaths.API_GATEWAY_REST, event);
const custom = search('metadata.tracking.id', event);

Usage Patterns:

// With setCorrelationId
logger.setCorrelationId(event, correlationPaths.API_GATEWAY_REST);

// With middleware
export const handler = middy(lambdaHandler).use(
  injectLambdaContext(logger, {
    correlationIdPath: correlationPaths.API_GATEWAY_REST
  })
);

// With constructor
const logger = new Logger({
  serviceName: 'myService',
  correlationIdSearchFn: (event) => search(correlationPaths.API_GATEWAY_HTTP, event)
});

// Direct search
const id = search(correlationPaths.EVENT_BRIDGE, event);
logger.appendKeys({ correlationId: id });

Custom Log Formatters

import { LogFormatter, LogItem } from '@aws-lambda-powertools/logger';

abstract class LogFormatter {
  abstract formatAttributes(
    attributes: UnformattedAttributes,
    additionalLogAttributes: LogAttributes
  ): LogItem;

  formatError(error: Error): LogAttributes;
  formatTimestamp(now: Date): string;
  getCodeLocation(stack?: string): string;
}

class LogItem {
  constructor(params: { attributes: LogAttributes });
  addAttributes(attributes: LogAttributes): this;
  getAttributes(): LogAttributes;
  setAttributes(attributes: LogAttributes): void;
  prepareForPrint(): void;
  removeEmptyKeys(attributes: LogAttributes): LogAttributes;
}

Create Custom Formatter:

import type { UnformattedAttributes } from '@aws-lambda-powertools/logger/types';

class CustomFormatter extends LogFormatter {
  public formatAttributes(
    attributes: UnformattedAttributes,
    additionalLogAttributes: LogAttributes
  ): LogItem {
    return new LogItem({
      attributes: {
        '@timestamp': this.formatTimestamp(attributes.timestamp),
        'level': attributes.logLevel,
        'message': attributes.message,
        'service': attributes.serviceName
      }
    }).addAttributes(additionalLogAttributes);
  }
}

const logger = new Logger({
  serviceName: 'myService',
  logFormatter: new CustomFormatter()
});

TypeScript Types

type LogLevel =
  | 'TRACE' | 'DEBUG' | 'INFO' | 'WARN' | 'ERROR' | 'CRITICAL' | 'SILENT'
  | 'trace' | 'debug' | 'info' | 'warn' | 'error' | 'critical' | 'silent';

type LogAttributes = { [key: string]: unknown };

type LogItemMessage = string | (LogAttributes & { message: string });

type LogItemExtraInput = [Error | string] | LogAttributes[];

type ConstructorOptions = {
  logLevel?: LogLevel;
  serviceName?: string;
  sampleRateValue?: number;
  customConfigService?: ConfigServiceInterface;
  environment?: string;
  persistentKeys?: LogAttributes;
  logFormatter?: LogFormatter;
  logRecordOrder?: string[] | Set<string>;
  jsonReplacerFn?: CustomJsonReplacerFn;
  logBufferOptions?: LogBufferOptions;
  correlationIdSearchFn?: (event: unknown) => string;
};

type LogBufferOptions = {
  enabled?: boolean;
  maxBytes?: number;
  flushOnErrorLog?: boolean;
  bufferAtVerbosity?: 'DEBUG' | 'INFO' | 'WARN' | 'debug' | 'info' | 'warn';
};

type InjectLambdaContextOptions = {
  logEvent?: boolean;
  resetKeys?: boolean;
  flushBufferOnUncaughtError?: boolean;
  correlationIdPath?: string;
};

type UnformattedAttributes = {
  logLevel: string;
  message: string;
  timestamp: Date;
  serviceName?: string;
  sampleRateValue?: number;
  xRayTraceId?: string;
  lambdaContext?: {
    functionName?: string;
    memoryLimitInMB?: number;
    invokedFunctionArn?: string;
    awsRequestId?: string;
    coldStart?: boolean;
  };
  error?: Error;
};

type CustomJsonReplacerFn = (key: string, value: unknown) => unknown;

Deprecated Methods

These methods are deprecated but still functional. Use the recommended alternatives.

// Deprecated - Use appendPersistentKeys()
addPersistentLogAttributes(attributes: LogAttributes): void;
setPersistentLogAttributes(attributes: LogAttributes): void;

// Deprecated - Use removePersistentKeys()
removePersistentLogAttributes(keys: string[]): void;

// Deprecated - Use getPersistentLogAttributes()
get persistentLogAttributes(): LogAttributes;

InjectLambdaContextOptions:

clearState?: boolean; // Deprecated - Use resetKeys instead