or run

npx @tessl/cli init
Log in

Version

Tile

Overview

Evals

Files

docs

aws-sdk-instrumentation.mddecorator-tracing.mdindex.mdmanual-instrumentation.mdmiddleware-tracing.mdtypes.md
tile.json

tessl/npm-aws-lambda-powertools--tracer

Opinionated thin wrapper for AWS X-Ray SDK enabling distributed tracing in AWS Lambda functions with automatic cold start capture and AWS SDK instrumentation

Workspace
tessl
Visibility
Public
Created
Last updated
Describes
npmpkg:npm/@aws-lambda-powertools/tracer@2.29.x

To install, run

npx @tessl/cli install tessl/npm-aws-lambda-powertools--tracer@2.29.0

index.mddocs/

AWS Lambda Powertools Tracer

AWS Lambda Powertools Tracer is an opinionated thin wrapper for the AWS X-Ray SDK for Node.js, specifically designed for AWS Lambda functions. It enables distributed tracing with minimal boilerplate by automatically capturing Lambda cold starts, tracing HTTP(S) clients including fetch, and instrumenting AWS SDK v3 clients. The library provides decorator-based, middleware-based, and manual instrumentation patterns for comprehensive observability in serverless applications.

Package Information

  • Package Name: @aws-lambda-powertools/tracer
  • Package Type: npm
  • Language: TypeScript
  • Installation: npm install @aws-lambda-powertools/tracer

Core Imports

import { Tracer } from '@aws-lambda-powertools/tracer';

For middleware:

import { captureLambdaHandler } from '@aws-lambda-powertools/tracer/middleware';

For types:

import type {
  TracerOptions,
  CaptureLambdaHandlerOptions,
  CaptureMethodOptions,
  TracerInterface
} from '@aws-lambda-powertools/tracer/types';

CommonJS:

const { Tracer } = require('@aws-lambda-powertools/tracer');
const { captureLambdaHandler } = require('@aws-lambda-powertools/tracer/middleware');

Basic Usage

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

const tracer = new Tracer({ serviceName: 'serverlessAirline' });

class Lambda implements LambdaInterface {
  @tracer.captureLambdaHandler()
  public async handler(_event: unknown, _context: unknown): Promise<void> {
    // Add custom annotations and metadata
    tracer.putAnnotation('successfulBooking', true);
    tracer.putMetadata('bookingDetails', { id: '123', status: 'confirmed' });

    // Your business logic here
  }
}

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

Architecture

The Tracer library is built around several key components:

  • Tracer Class: Main interface providing all tracing functionality including decorators, manual instrumentation, and configuration
  • Provider Service: Internal wrapper around AWS X-Ray SDK that handles low-level segment management and instrumentation
  • Decorator Pattern: TypeScript decorators for automatic tracing of Lambda handlers and class methods
  • Middleware Integration: Middy middleware for function-based handlers
  • Automatic Instrumentation: Built-in support for HTTP(S) clients, fetch API, and AWS SDK v3
  • Environment-Aware: Automatically disables tracing in non-Lambda environments (SAM Local, Amplify CLI, local development)

Capabilities

Tracer Initialization

Initialize the Tracer with configuration options to control tracing behavior.

/**
 * Creates a new Tracer instance with optional configuration
 */
class Tracer {
  constructor(options?: TracerOptions);
}

interface TracerOptions {
  /** Enable or disable tracing (default: true in Lambda, false otherwise) */
  enabled?: boolean;
  /** Service name for traces (can also be set via POWERTOOLS_SERVICE_NAME env var) */
  serviceName?: string;
  /** Whether to trace outgoing HTTP requests made with http, https, or fetch (default: true) */
  captureHTTPsRequests?: boolean;
  /** Custom configuration service for advanced use cases */
  customConfigService?: ConfigServiceInterface;
}

Decorator-based Tracing

Middleware-based Tracing

Automatic tracing for function-based Lambda handlers using Middy middleware.

/**
 * Middy middleware that automatically traces Lambda handler execution
 */
function captureLambdaHandler(
  target: Tracer,
  options?: CaptureLambdaHandlerOptions
): MiddlewareLikeObj;

interface CaptureLambdaHandlerOptions {
  /** Whether to capture the Lambda handler response as subsegment metadata (default: true) */
  captureResponse?: boolean;
}

Middleware Integration

Manual Instrumentation

Direct control over segment and subsegment lifecycle for custom tracing scenarios.

/**
 * Get the active segment or subsegment in the current scope
 */
getSegment(): Segment | Subsegment | undefined;

/**
 * Set the passed subsegment as the current active subsegment
 */
setSegment(segment: Segment | Subsegment): void;

Manual Instrumentation

Annotations and Metadata

Add searchable annotations and detailed metadata to traces.

/**
 * Add annotation to existing segment or subsegment (searchable in X-Ray console)
 */
putAnnotation(key: string, value: string | number | boolean): void;

/**
 * Add metadata to existing segment or subsegment (not searchable but visible in trace details)
 */
putMetadata(key: string, value: unknown, namespace?: string): void;

/**
 * Add service name to the current segment or subsegment as annotation
 */
addServiceNameAnnotation(): void;

/**
 * Add ColdStart annotation to the current segment or subsegment
 */
annotateColdStart(): void;

/**
 * Add error to the current segment or subsegment as metadata
 */
addErrorAsMetadata(error: Error, remote?: boolean): void;

/**
 * Add response data to the current segment or subsegment as metadata
 */
addResponseAsMetadata(data?: unknown, methodName?: string): void;

AWS SDK Instrumentation

Automatically trace AWS SDK v3 client calls to capture service interactions.

/**
 * Patch an AWS SDK v3 client to create traces for AWS service calls
 */
captureAWSv3Client<T>(service: T): T;

/**
 * @deprecated Use captureAWSv3Client instead
 * Patch all AWS SDK v2 clients
 */
captureAWS<T>(aws: T): T;

/**
 * @deprecated Use captureAWSv3Client instead
 * Patch a specific AWS SDK v2 client
 */
captureAWSClient<T>(service: T): T;

AWS SDK Instrumentation

Tracing Utilities

Utility methods for trace inspection and configuration.

/**
 * Get the current root AWS X-Ray trace id (useful as correlation id)
 */
getRootXrayTraceId(): string | undefined;

/**
 * Get the current value of the AWS X-Ray Sampled flag
 */
isTraceSampled(): boolean;

/**
 * Get the current value of the tracingEnabled property
 */
isTracingEnabled(): boolean;

Provider Service Access

Access to the underlying provider service for advanced use cases.

/**
 * The provider service interface used by the Tracer
 */
provider: ProviderServiceInterface;

Type Definitions

Environment Variables

The Tracer respects the following environment variables:

  • POWERTOOLS_SERVICE_NAME - Service name for traces (overridden by constructor option)
  • POWERTOOLS_TRACE_ENABLED - Enable/disable tracing (true or false)
  • POWERTOOLS_TRACER_CAPTURE_RESPONSE - Capture response as metadata (true or false, default: true)
  • POWERTOOLS_TRACER_CAPTURE_ERROR - Capture error as metadata (true or false, default: true)
  • POWERTOOLS_TRACER_CAPTURE_HTTPS_REQUESTS - Capture HTTP(S) requests (true or false, default: true)
  • AWS_EXECUTION_ENV - AWS execution environment (automatically set by Lambda)
  • AWS_SAM_LOCAL - SAM local indicator (automatically set by SAM CLI)
  • _HANDLER - Lambda handler name (automatically set by Lambda)
  • _X_AMZN_TRACE_ID - X-Ray trace ID (automatically set by Lambda)