Intro

Tracer is an opinionated thin wrapper for AWS X-Ray SDK for Node.js.

Tracing data can be visualized through AWS X-Ray Console.

Key features

  • Auto capture cold start as annotation, and responses or full exceptions as metadata
  • Auto-disable when not running in AWS Lambda environment
  • Automatically trace HTTP(s) clients and generate segments for each request
  • Support tracing functions via decorators, middleware, and manual instrumentation
  • Support tracing AWS SDK v2 and v3 via AWS X-Ray SDK for Node.js

Usage

For more usage examples, see our documentation.

Functions usage with middleware

If you use function-based Lambda handlers you can use the captureLambdaHandler() middy middleware to automatically:

  • handle the subsegment lifecycle
  • add the ServiceName and ColdStart annotations
  • add the function response as metadata
  • add the function error as metadata (if any)

Example

import { captureLambdaHandler, Tracer } from '@aws-lambda-powertools/tracer';
import middy from '@middy/core';

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

const lambdaHandler = async (_event: any, _context: any) => {
...
};

export const handler = middy(lambdaHandler).use(captureLambdaHandler(tracer));

Object oriented usage with decorators

If instead you use TypeScript Classes to wrap your Lambda handler you can use the @tracer.captureLambdaHandler() decorator to automatically:

  • handle the subsegment lifecycle
  • add the ServiceName and ColdStart annotations
  • add the function response as metadata
  • add the function error as metadata (if any)

Example

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

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

// FYI: Decorator might not render properly in VSCode mouse over due to https://github.com/microsoft/TypeScript/issues/47679 and might show as *@tracer* instead of `@tracer.captureLambdaHandler`

class Lambda implements LambdaInterface {
@tracer.captureLambdaHandler()
public handler(event: any, context: any) {
...
}
}

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 tracer class directly.

Example

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

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

export const handler = async (_event: any, context: any) => {
const segment = tracer.getSegment(); // This is the facade segment (the one that is created by AWS Lambda)
// Create subsegment for the function & set it as active
const subsegment = segment.addNewSubsegment(`## ${process.env._HANDLER}`);
tracer.setSegment(subsegment);

// Annotate the subsegment with the cold start & serviceName
tracer.annotateColdStart();
tracer.addServiceNameAnnotation();

let res;
try {
// ... your own logic goes here
// Add the response as metadata
tracer.addResponseAsMetadata(res, process.env._HANDLER);
} catch (err) {
// Add the error as metadata
tracer.addErrorAsMetadata(err as Error);
throw err;
} finally {
// Close the subsegment
subsegment.close();
// Set the facade segment as active again
tracer.setSegment(segment);
}

return res;
}

Hierarchy

Implements

Constructors

Properties

provider: ProviderServiceInterface

Methods

  • Patch a specific AWS SDK v2 client and create traces when your application makes calls to that AWS service.

    If you want to patch all clients use captureAWS and if you are using AWS SDK v3 use captureAWSv3Client instead.

    Type Parameters

    • T

    Parameters

    • service: T

      AWS SDK v2 client

    Returns T

    service - Instrumented AWS SDK v2 client

    See

    https://docs.aws.amazon.com/xray/latest/devguide/xray-sdk-nodejs-awssdkclients.html

    Example

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

    const tracer = new Tracer({ serviceName: 'serverlessAirline' });
    const s3 = tracer.captureAWSClient(new S3({ apiVersion: '2006-03-01' }));

    export const handler = async (_event: any, _context: any) => {
    ...
    }
  • Patch an AWS SDK v3 client and create traces when your application makes calls to that AWS service.

    If you are using AWS SDK v2 use captureAWSClient instead.

    Type Parameters

    • T

    Parameters

    • service: T

      AWS SDK v3 client

    Returns T

    service - Instrumented AWS SDK v3 client

    See

    https://docs.aws.amazon.com/xray/latest/devguide/xray-sdk-nodejs-awssdkclients.html

    Example

    import { S3Client } from '@aws-sdk/client-s3';
    import { Tracer } from '@aws-lambda-powertools/tracer';

    const tracer = new Tracer({ serviceName: 'serverlessAirline' });
    const client = new S3Client({});
    tracer.captureAWSv3Client(client);

    export const handler = async (_event: any, _context: any) => {
    ...
    }
  • A decorator automating capture of metadata and annotations on segments or subsegments for a Lambda Handler.

    Using this decorator on your handler function will automatically:

    • handle the subsegment lifecycle
    • add the ColdStart annotation
    • add the function response as metadata
    • add the function error as metadata (if any)

    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 { Tracer } from '@aws-lambda-powertools/tracer';
    import { LambdaInterface } from '@aws-lambda-powertools/commons';

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

    class Lambda implements LambdaInterface {
    @tracer.captureLambdaHandler()
    public handler(event: any, context: any) {
    ...
    }
    }

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

    Decorator

    Class

  • A decorator automating capture of metadata and annotations on segments or subsegments for an arbitrary function.

    Using this decorator on your function will automatically:

    • handle the subsegment lifecycle
    • add the function response as metadata
    • add the function error as metadata (if any)

    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 MethodDecorator

    Example

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

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

    class Lambda implements LambdaInterface {
    @tracer.captureMethod()
    public myMethod(param: any) {
    ...
    }

    public handler(event: any, context: any) {
    ...
    }
    }

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

    Decorator

    Class

  • Returns boolean

  • Get the current root AWS X-Ray trace id.

    Utility method that returns the current AWS X-Ray Root trace id. Useful as correlation id for downstream processes.

    Returns undefined | string

    string - The root X-Ray trace id.

    See

    https://docs.aws.amazon.com/xray/latest/devguide/xray-concepts.html#xray-concepts-traces

    Example

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

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

    export const handler = async () => {
    try {
    ...
    } catch (err) {
    const rootTraceId = tracer.getRootXrayTraceId();

    // Example of returning an error response
    return {
    statusCode: 500,
    // Include the rootTraceId in the response so we can show a "contact support" button that
    // takes the customer to a customer service form with the trace as additional context.
    body: `Internal Error - Please contact support and quote the following id: ${rootTraceId}`,
    headers: { '_X_AMZN_TRACE_ID': rootTraceId },
    };
    }
    }
  • Returns boolean

  • Get the current value of the tracingEnabled property.

    You can use this method during manual instrumentation to determine if tracer is currently enabled.

    Returns boolean

    tracingEnabled - true if tracing is enabled, false otherwise.

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

    Parameters

    • Optional serviceName: string

      Service name to validate

    Returns boolean

  • Sets the passed subsegment as the current active subsegment.

    If you are using a middleware or a decorator this is done automatically for you.

    Parameters

    • segment: Segment | Subsegment

      Subsegment to set as the current segment

    Returns void

    See

    https://docs.aws.amazon.com/xray/latest/devguide/xray-sdk-nodejs-subsegments.html

    Example

    import { Tracer } from '@aws-lambda-powertools/tracer';
    import { Subsegment } from 'aws-xray-sdk-core';

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

    export const handler = async (_event: any, _context: any) => {
    const subsegment = new Subsegment('### foo.bar');
    tracer.setSegment(subsegment);
    }

Generated using TypeDoc