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

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

  • 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

For more usage examples, see our documentation.

If you use function-based Lambda handlers you can use the Tracer.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)
import { Tracer } from '@aws-lambda-powertools/tracer';
import { captureLambdaHandler } from '@aws-lambda-powertools/tracer/middleware';
import middy from '@middy/core';

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

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

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

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)
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 handler(_event: unknown, _context: unknown) {
...
}
}

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

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

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

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

export const handler = async (_event: unknown, _context: unknown) => {
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 (View Summary)

Implements

Constructors

Properties

The provider service interface used by the Tracer. This interface defines the methods and properties that a provider service must implement.

Methods

  • 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

    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 handler(_event: unknown, _context: unknown) {
    // ...
    }
    }

    const handlerClass = new Lambda();
    export const handler = handlerClass.handler.bind(handlerClass);
  • 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.

    Type Parameters

    Parameters

    Returns MethodDecorator<T>

    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: string) {
    // ...
    }

    public handler(_event: unknown, _context: unknown) {
    this.myMethod('foo');
    }
    }

    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

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

  • Get the default service name.

    Returns string

  • 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

    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 },
    };
    }
    }
  • 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
  • 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

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

    Parameters

    • OptionalserviceName: string

      Service name to validate

    Returns boolean

  • Set 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

    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: unknown, _context: unknown) => {
    const subsegment = new Subsegment('### foo.bar');
    tracer.setSegment(subsegment);
    }