πŸš€ Big News: Socket Acquires Coana to Bring Reachability Analysis to Every Appsec Team.Learn more β†’

@aws-lambda-powertools/tracer

Advanced tools

Socket logo

Install Socket

Detect and block malicious and high-risk dependencies

Install

@aws-lambda-powertools/tracer - npm Package Compare versions

Comparing version

to
2.8.0

import type { Segment, Subsegment } from 'aws-xray-sdk-core';
import type { Namespace } from 'cls-hooked';
import type { ContextMissingStrategy, ProviderServiceInterface } from '../types/ProviderService.js';
/**
* The ProviderService class is a wrapper around the AWS X-Ray SDK for Node.js.
*
* The service provides exposes a selection of methods to interact with the SDK directly,
* these methods were chosen to be the most useful in the context of a Lambda function and
* have been tested to work with Powertools for AWS Lambda.
*
* If you want to use one of the other methods that are not exposed by this class,
* you can import the methods directly from the `aws-xray-sdk-core` package, and for most cases,
* they should work as expected. However, support for these methods is not guaranteed.
*/
declare class ProviderService implements ProviderServiceInterface {

@@ -5,0 +16,0 @@ /**

@@ -14,2 +14,13 @@ "use strict";

const utilities_js_1 = require("./utilities.js");
/**
* The ProviderService class is a wrapper around the AWS X-Ray SDK for Node.js.
*
* The service provides exposes a selection of methods to interact with the SDK directly,
* these methods were chosen to be the most useful in the context of a Lambda function and
* have been tested to work with Powertools for AWS Lambda.
*
* If you want to use one of the other methods that are not exposed by this class,
* you can import the methods directly from the `aws-xray-sdk-core` package, and for most cases,
* they should work as expected. However, support for these methods is not guaranteed.
*/
class ProviderService {

@@ -65,3 +76,3 @@ /**

*
* @note that `message` must be `unknown` because that's the type expected by `subscribe`
* That `message` must be `unknown` because that's the type expected by `subscribe`
*

@@ -73,10 +84,10 @@ * @param message The message received from the `undici` channel

const parentSubsegment = this.getSegment();
if (parentSubsegment && request.origin) {
const origin = (0, utilities_js_1.getOriginURL)(request.origin);
const requestURL = (0, utilities_js_1.getRequestURL)(request);
if (parentSubsegment && requestURL) {
const method = request.method;
const subsegment = parentSubsegment.addNewSubsegment(origin.hostname);
const subsegment = parentSubsegment.addNewSubsegment(requestURL.hostname);
subsegment.addAttribute('namespace', 'remote');
subsegment.http = {
request: {
url: origin.hostname,
url: `${requestURL.protocol}//${requestURL.hostname}${requestURL.pathname}`,
method,

@@ -92,3 +103,3 @@ },

*
* @note that `message` must be `unknown` because that's the type expected by `subscribe`
* `message` must be `unknown` because that's the type expected by `subscribe`
*

@@ -131,3 +142,3 @@ * @param message The message received from the `undici` channel

*
* @note that `message` must be `unknown` because that's the type expected by `subscribe`
* that `message` must be `unknown` because that's the type expected by `subscribe`
*

@@ -134,0 +145,0 @@ * @param message The message received from the `undici` channel

import { URL } from 'node:url';
import type { Segment, Subsegment } from 'aws-xray-sdk-core';
import type { DiagnosticsChannel } from 'undici-types';
import type { HttpSubsegment } from '../types/ProviderService.js';

@@ -22,8 +23,8 @@ /**

/**
* Convert the origin url to a URL object when it is a string
* Convert the origin url to a URL object when it is a string and append the path if provided
*
* @param origin The origin url
* @param origin The request object containing the origin url and path
*/
declare const getOriginURL: (origin: string | URL) => URL;
export { findHeaderAndDecode, isHttpSubsegment, getOriginURL };
declare const getRequestURL: (request: DiagnosticsChannel.Request) => URL | undefined;
export { findHeaderAndDecode, isHttpSubsegment, getRequestURL };
//# sourceMappingURL=utilities.d.ts.map
"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
exports.getOriginURL = exports.isHttpSubsegment = exports.findHeaderAndDecode = void 0;
exports.getRequestURL = exports.isHttpSubsegment = exports.findHeaderAndDecode = void 0;
const node_url_1 = require("node:url");

@@ -45,9 +45,16 @@ const decoder = new TextDecoder();

/**
* Convert the origin url to a URL object when it is a string
* Convert the origin url to a URL object when it is a string and append the path if provided
*
* @param origin The origin url
* @param origin The request object containing the origin url and path
*/
const getOriginURL = (origin) => {
return origin instanceof node_url_1.URL ? origin : new node_url_1.URL(origin);
const getRequestURL = (request) => {
if (typeof request.origin === 'string') {
return new node_url_1.URL(`${request.origin}${request.path || ''}`);
}
if (request.origin instanceof node_url_1.URL) {
request.origin.pathname = request.path || '';
return request.origin;
}
return undefined;
};
exports.getOriginURL = getOriginURL;
exports.getRequestURL = getRequestURL;

@@ -25,3 +25,3 @@ import { Utility } from '@aws-lambda-powertools/commons';

*
* If you use function-based Lambda handlers you can use the [captureLambdaHandler()](./_aws_lambda_powertools_tracer.Tracer.html) middy middleware to automatically:
* If you use function-based Lambda handlers you can use the {@link Tracer.captureLambdaHandler} middy middleware to automatically:
* * handle the subsegment lifecycle

@@ -49,3 +49,3 @@ * * add the `ServiceName` and `ColdStart` annotations

*
* If instead you use TypeScript Classes to wrap your Lambda handler you can use the [@tracer.captureLambdaHandler()](./_aws_lambda_powertools_tracer.Tracer.html#captureLambdaHandler) decorator to automatically:
* If instead you use TypeScript Classes to wrap your Lambda handler you can use the {@link Tracer.captureLambdaHandler} decorator to automatically:
* * handle the subsegment lifecycle

@@ -115,9 +115,40 @@ * * add the `ServiceName` and `ColdStart` annotations

declare class Tracer extends Utility implements TracerInterface {
/**
* The provider service interface used by the Tracer.
* This interface defines the methods and properties that a provider service must implement.
*/
provider: ProviderServiceInterface;
/**
* Flag indicating whether to capture errors.
* This is used to determine if errors should be added to the trace as metadata.
*
* @default true
*/
private captureError;
/**
* Flag indicating whether to capture HTTP(s) requests.
* @default true
*/
private captureHTTPsRequests;
/**
* Flag indicating whether to capture response data.
* @default true
*/
private captureResponse;
/**
* The custom configuration service used by the Tracer.
*/
private customConfigService?;
/**
* The environment variables service used by the Tracer, is always initialized in the constructor in setOptions().
*/
private envVarsService;
/**
* The name of the service, is always initialized in the constructor in setOptions().
*/
private serviceName;
/**
* Flag indicating whether tracing is enabled.
* @default true
*/
private tracingEnabled;

@@ -145,3 +176,2 @@ constructor(options?: TracerOptions);

* Add service name to the current segment or subsegment as annotation.
*
*/

@@ -180,3 +210,2 @@ addServiceNameAnnotation(): void;

* @param aws - AWS SDK v2 import
* @returns AWS - Instrumented AWS SDK
*/

@@ -205,3 +234,2 @@ captureAWS<T>(aws: T): T;

* @param service - AWS SDK v2 client
* @returns service - Instrumented AWS SDK v2 client
*/

@@ -231,3 +259,2 @@ captureAWSClient<T>(service: T): T;

* @param service - AWS SDK v3 client
* @returns service - Instrumented AWS SDK v3 client
*/

@@ -265,3 +292,2 @@ captureAWSv3Client<T>(service: T): T;

*
* @decorator Class
* @param options - (_optional_) Options for the decorator

@@ -303,3 +329,2 @@ */

*
* @decorator Class
* @param options - (_optional_) Options for the decorator

@@ -338,4 +363,2 @@ */

* ```
*
* @returns string - The root X-Ray trace id.
*/

@@ -362,4 +385,2 @@ getRootXrayTraceId(): string | undefined;

* ```
*
* @returns The active segment or subsegment in the current scope. Will log a warning and return `undefined` if no segment is found.
*/

@@ -373,4 +394,2 @@ getSegment(): Segment | Subsegment | undefined;

* @see https://docs.aws.amazon.com/xray/latest/devguide/xray-concepts.html#xray-concepts-traces
*
* @returns boolean - `true` if the trace is sampled, `false` if tracing is disabled or the trace is not sampled.
*/

@@ -383,8 +402,6 @@ isTraceSampled(): boolean;

* if tracer is currently enabled.
*
* @returns tracingEnabled - `true` if tracing is enabled, `false` otherwise.
*/
isTracingEnabled(): boolean;
/**
* Adds annotation to existing segment or subsegment.
* Add annotation to existing segment or subsegment.
*

@@ -409,3 +426,3 @@ * @see https://docs.aws.amazon.com/xray/latest/devguide/xray-sdk-nodejs-segment.html#xray-sdk-nodejs-segment-annotations

/**
* Adds metadata to existing segment or subsegment.
* Add metadata to existing segment or subsegment.
*

@@ -432,3 +449,3 @@ * @see https://docs.aws.amazon.com/xray/latest/devguide/xray-sdk-nodejs-segment.html#xray-sdk-nodejs-segment-metadata

/**
* Sets the passed subsegment as the current active subsegment.
* Set the passed subsegment as the current active subsegment.
*

@@ -461,3 +478,3 @@ * If you are using a middleware or a decorator this is done automatically for you.

/**
* Getter for `envVarsService`.
* Get for `envVarsService`.
* Used internally during initialization.

@@ -482,3 +499,3 @@ */

/**
* Setter for `captureError` based on configuration passed and environment variables.
* Set `captureError` based on configuration passed and environment variables.
* Used internally during initialization.

@@ -496,7 +513,6 @@ */

* @param enabled - Whether or not to patch all HTTP clients
* @returns void
*/
private setCaptureHTTPsRequests;
/**
* Setter for `captureResponse` based on configuration passed and environment variables.
* Set `captureResponse` based on configuration passed and environment variables.
* Used internally during initialization.

@@ -506,3 +522,3 @@ */

/**
* Setter for `customConfigService` based on configuration passed.
* Set `customConfigService` based on configuration passed.
* Used internally during initialization.

@@ -514,3 +530,3 @@ *

/**
* Setter and initializer for `envVarsService`.
* Set and initialize `envVarsService`.
* Used internally during initialization.

@@ -527,3 +543,3 @@ */

/**
* Setter for `customConfigService` based on configurations passed and environment variables.
* Set `customConfigService` based on configurations passed and environment variables.
* Used internally during initialization.

@@ -535,3 +551,3 @@ *

/**
* Setter for `tracingEnabled` based on configurations passed and environment variables.
* Set `tracingEnabled` based on configurations passed and environment variables.
* Used internally during initialization.

@@ -538,0 +554,0 @@ *

@@ -7,2 +7,12 @@ "use strict";

exports.Tracer = void 0;
/**
* If the AWS_XRAY_CONTEXT_MISSING environment variable is not set, we set it to IGNORE_ERROR.
*
* This is to prevent the AWS X-Ray SDK from logging errors when using top-level await features that make HTTP requests.
* For example, when using the Parameters utility to fetch parameters during the initialization of the Lambda handler - See #2046
*/
if (process.env.AWS_XRAY_CONTEXT_MISSING === '' ||
process.env.AWS_XRAY_CONTEXT_MISSING === undefined) {
process.env.AWS_XRAY_CONTEXT_MISSING = 'IGNORE_ERROR';
}
const commons_1 = require("@aws-lambda-powertools/commons");

@@ -32,3 +42,3 @@ const aws_xray_sdk_core_1 = __importDefault(require("aws-xray-sdk-core"));

*
* If you use function-based Lambda handlers you can use the [captureLambdaHandler()](./_aws_lambda_powertools_tracer.Tracer.html) middy middleware to automatically:
* If you use function-based Lambda handlers you can use the {@link Tracer.captureLambdaHandler} middy middleware to automatically:
* * handle the subsegment lifecycle

@@ -56,3 +66,3 @@ * * add the `ServiceName` and `ColdStart` annotations

*
* If instead you use TypeScript Classes to wrap your Lambda handler you can use the [@tracer.captureLambdaHandler()](./_aws_lambda_powertools_tracer.Tracer.html#captureLambdaHandler) decorator to automatically:
* If instead you use TypeScript Classes to wrap your Lambda handler you can use the {@link Tracer.captureLambdaHandler} decorator to automatically:
* * handle the subsegment lifecycle

@@ -122,11 +132,41 @@ * * add the `ServiceName` and `ColdStart` annotations

class Tracer extends commons_1.Utility {
/**
* The provider service interface used by the Tracer.
* This interface defines the methods and properties that a provider service must implement.
*/
provider;
/**
* Flag indicating whether to capture errors.
* This is used to determine if errors should be added to the trace as metadata.
*
* @default true
*/
captureError = true;
/**
* Flag indicating whether to capture HTTP(s) requests.
* @default true
*/
captureHTTPsRequests = true;
/**
* Flag indicating whether to capture response data.
* @default true
*/
captureResponse = true;
/**
* The custom configuration service used by the Tracer.
*/
customConfigService;
// envVarsService is always initialized in the constructor in setOptions()
/**
* The environment variables service used by the Tracer, is always initialized in the constructor in setOptions().
*/
envVarsService;
// serviceName is always initialized in the constructor in setOptions()
/**
* The name of the service, is always initialized in the constructor in setOptions().
*/
serviceName;
/**
* Flag indicating whether tracing is enabled.
* @default true
*/
tracingEnabled = true;

@@ -186,3 +226,2 @@ constructor(options = {}) {

* Add service name to the current segment or subsegment as annotation.
*
*/

@@ -230,3 +269,2 @@ addServiceNameAnnotation() {

* @param aws - AWS SDK v2 import
* @returns AWS - Instrumented AWS SDK
*/

@@ -259,3 +297,2 @@ captureAWS(aws) {

* @param service - AWS SDK v2 client
* @returns service - Instrumented AWS SDK v2 client
*/

@@ -303,3 +340,2 @@ captureAWSClient(service) {

* @param service - AWS SDK v3 client
* @returns service - Instrumented AWS SDK v3 client
*/

@@ -341,3 +377,2 @@ captureAWSv3Client(service) {

*
* @decorator Class
* @param options - (_optional_) Options for the decorator

@@ -421,3 +456,2 @@ */

*
* @decorator Class
* @param options - (_optional_) Options for the decorator

@@ -497,4 +531,2 @@ */

* ```
*
* @returns string - The root X-Ray trace id.
*/

@@ -523,4 +555,2 @@ getRootXrayTraceId() {

* ```
*
* @returns The active segment or subsegment in the current scope. Will log a warning and return `undefined` if no segment is found.
*/

@@ -543,4 +573,2 @@ getSegment() {

* @see https://docs.aws.amazon.com/xray/latest/devguide/xray-concepts.html#xray-concepts-traces
*
* @returns boolean - `true` if the trace is sampled, `false` if tracing is disabled or the trace is not sampled.
*/

@@ -557,4 +585,2 @@ isTraceSampled() {

* if tracer is currently enabled.
*
* @returns tracingEnabled - `true` if tracing is enabled, `false` otherwise.
*/

@@ -565,3 +591,3 @@ isTracingEnabled() {

/**
* Adds annotation to existing segment or subsegment.
* Add annotation to existing segment or subsegment.
*

@@ -590,3 +616,3 @@ * @see https://docs.aws.amazon.com/xray/latest/devguide/xray-sdk-nodejs-segment.html#xray-sdk-nodejs-segment-annotations

/**
* Adds metadata to existing segment or subsegment.
* Add metadata to existing segment or subsegment.
*

@@ -617,3 +643,3 @@ * @see https://docs.aws.amazon.com/xray/latest/devguide/xray-sdk-nodejs-segment.html#xray-sdk-nodejs-segment-metadata

/**
* Sets the passed subsegment as the current active subsegment.
* Set the passed subsegment as the current active subsegment.
*

@@ -652,3 +678,3 @@ * If you are using a middleware or a decorator this is done automatically for you.

/**
* Getter for `envVarsService`.
* Get for `envVarsService`.
* Used internally during initialization.

@@ -682,3 +708,3 @@ */

/**
* Setter for `captureError` based on configuration passed and environment variables.
* Set `captureError` based on configuration passed and environment variables.
* Used internally during initialization.

@@ -708,3 +734,2 @@ */

* @param enabled - Whether or not to patch all HTTP clients
* @returns void
*/

@@ -729,3 +754,3 @@ setCaptureHTTPsRequests(enabled) {

/**
* Setter for `captureResponse` based on configuration passed and environment variables.
* Set `captureResponse` based on configuration passed and environment variables.
* Used internally during initialization.

@@ -747,3 +772,3 @@ */

/**
* Setter for `customConfigService` based on configuration passed.
* Set `customConfigService` based on configuration passed.
* Used internally during initialization.

@@ -759,3 +784,3 @@ *

/**
* Setter and initializer for `envVarsService`.
* Set and initialize `envVarsService`.
* Used internally during initialization.

@@ -784,3 +809,3 @@ */

/**
* Setter for `customConfigService` based on configurations passed and environment variables.
* Set `customConfigService` based on configurations passed and environment variables.
* Used internally during initialization.

@@ -809,3 +834,3 @@ *

/**
* Setter for `tracingEnabled` based on configurations passed and environment variables.
* Set `tracingEnabled` based on configurations passed and environment variables.
* Used internally during initialization.

@@ -812,0 +837,0 @@ *

import type { Segment, Subsegment } from 'aws-xray-sdk-core';
import type { Namespace } from 'cls-hooked';
import type { ContextMissingStrategy, ProviderServiceInterface } from '../types/ProviderService.js';
/**
* The ProviderService class is a wrapper around the AWS X-Ray SDK for Node.js.
*
* The service provides exposes a selection of methods to interact with the SDK directly,
* these methods were chosen to be the most useful in the context of a Lambda function and
* have been tested to work with Powertools for AWS Lambda.
*
* If you want to use one of the other methods that are not exposed by this class,
* you can import the methods directly from the `aws-xray-sdk-core` package, and for most cases,
* they should work as expected. However, support for these methods is not guaranteed.
*/
declare class ProviderService implements ProviderServiceInterface {

@@ -5,0 +16,0 @@ /**

@@ -7,3 +7,14 @@ import xraySdk from 'aws-xray-sdk-core';

import { addUserAgentMiddleware } from '@aws-lambda-powertools/commons';
import { findHeaderAndDecode, getOriginURL, isHttpSubsegment, } from './utilities.js';
import { findHeaderAndDecode, getRequestURL, isHttpSubsegment, } from './utilities.js';
/**
* The ProviderService class is a wrapper around the AWS X-Ray SDK for Node.js.
*
* The service provides exposes a selection of methods to interact with the SDK directly,
* these methods were chosen to be the most useful in the context of a Lambda function and
* have been tested to work with Powertools for AWS Lambda.
*
* If you want to use one of the other methods that are not exposed by this class,
* you can import the methods directly from the `aws-xray-sdk-core` package, and for most cases,
* they should work as expected. However, support for these methods is not guaranteed.
*/
class ProviderService {

@@ -59,3 +70,3 @@ /**

*
* @note that `message` must be `unknown` because that's the type expected by `subscribe`
* That `message` must be `unknown` because that's the type expected by `subscribe`
*

@@ -67,10 +78,10 @@ * @param message The message received from the `undici` channel

const parentSubsegment = this.getSegment();
if (parentSubsegment && request.origin) {
const origin = getOriginURL(request.origin);
const requestURL = getRequestURL(request);
if (parentSubsegment && requestURL) {
const method = request.method;
const subsegment = parentSubsegment.addNewSubsegment(origin.hostname);
const subsegment = parentSubsegment.addNewSubsegment(requestURL.hostname);
subsegment.addAttribute('namespace', 'remote');
subsegment.http = {
request: {
url: origin.hostname,
url: `${requestURL.protocol}//${requestURL.hostname}${requestURL.pathname}`,
method,

@@ -86,3 +97,3 @@ },

*
* @note that `message` must be `unknown` because that's the type expected by `subscribe`
* `message` must be `unknown` because that's the type expected by `subscribe`
*

@@ -125,3 +136,3 @@ * @param message The message received from the `undici` channel

*
* @note that `message` must be `unknown` because that's the type expected by `subscribe`
* that `message` must be `unknown` because that's the type expected by `subscribe`
*

@@ -128,0 +139,0 @@ * @param message The message received from the `undici` channel

import { URL } from 'node:url';
import type { Segment, Subsegment } from 'aws-xray-sdk-core';
import type { DiagnosticsChannel } from 'undici-types';
import type { HttpSubsegment } from '../types/ProviderService.js';

@@ -22,8 +23,8 @@ /**

/**
* Convert the origin url to a URL object when it is a string
* Convert the origin url to a URL object when it is a string and append the path if provided
*
* @param origin The origin url
* @param origin The request object containing the origin url and path
*/
declare const getOriginURL: (origin: string | URL) => URL;
export { findHeaderAndDecode, isHttpSubsegment, getOriginURL };
declare const getRequestURL: (request: DiagnosticsChannel.Request) => URL | undefined;
export { findHeaderAndDecode, isHttpSubsegment, getRequestURL };
//# sourceMappingURL=utilities.d.ts.map

@@ -40,9 +40,16 @@ import { URL } from 'node:url';

/**
* Convert the origin url to a URL object when it is a string
* Convert the origin url to a URL object when it is a string and append the path if provided
*
* @param origin The origin url
* @param origin The request object containing the origin url and path
*/
const getOriginURL = (origin) => {
return origin instanceof URL ? origin : new URL(origin);
const getRequestURL = (request) => {
if (typeof request.origin === 'string') {
return new URL(`${request.origin}${request.path || ''}`);
}
if (request.origin instanceof URL) {
request.origin.pathname = request.path || '';
return request.origin;
}
return undefined;
};
export { findHeaderAndDecode, isHttpSubsegment, getOriginURL };
export { findHeaderAndDecode, isHttpSubsegment, getRequestURL };

@@ -25,3 +25,3 @@ import { Utility } from '@aws-lambda-powertools/commons';

*
* If you use function-based Lambda handlers you can use the [captureLambdaHandler()](./_aws_lambda_powertools_tracer.Tracer.html) middy middleware to automatically:
* If you use function-based Lambda handlers you can use the {@link Tracer.captureLambdaHandler} middy middleware to automatically:
* * handle the subsegment lifecycle

@@ -49,3 +49,3 @@ * * add the `ServiceName` and `ColdStart` annotations

*
* If instead you use TypeScript Classes to wrap your Lambda handler you can use the [@tracer.captureLambdaHandler()](./_aws_lambda_powertools_tracer.Tracer.html#captureLambdaHandler) decorator to automatically:
* If instead you use TypeScript Classes to wrap your Lambda handler you can use the {@link Tracer.captureLambdaHandler} decorator to automatically:
* * handle the subsegment lifecycle

@@ -115,9 +115,40 @@ * * add the `ServiceName` and `ColdStart` annotations

declare class Tracer extends Utility implements TracerInterface {
/**
* The provider service interface used by the Tracer.
* This interface defines the methods and properties that a provider service must implement.
*/
provider: ProviderServiceInterface;
/**
* Flag indicating whether to capture errors.
* This is used to determine if errors should be added to the trace as metadata.
*
* @default true
*/
private captureError;
/**
* Flag indicating whether to capture HTTP(s) requests.
* @default true
*/
private captureHTTPsRequests;
/**
* Flag indicating whether to capture response data.
* @default true
*/
private captureResponse;
/**
* The custom configuration service used by the Tracer.
*/
private customConfigService?;
/**
* The environment variables service used by the Tracer, is always initialized in the constructor in setOptions().
*/
private envVarsService;
/**
* The name of the service, is always initialized in the constructor in setOptions().
*/
private serviceName;
/**
* Flag indicating whether tracing is enabled.
* @default true
*/
private tracingEnabled;

@@ -145,3 +176,2 @@ constructor(options?: TracerOptions);

* Add service name to the current segment or subsegment as annotation.
*
*/

@@ -180,3 +210,2 @@ addServiceNameAnnotation(): void;

* @param aws - AWS SDK v2 import
* @returns AWS - Instrumented AWS SDK
*/

@@ -205,3 +234,2 @@ captureAWS<T>(aws: T): T;

* @param service - AWS SDK v2 client
* @returns service - Instrumented AWS SDK v2 client
*/

@@ -231,3 +259,2 @@ captureAWSClient<T>(service: T): T;

* @param service - AWS SDK v3 client
* @returns service - Instrumented AWS SDK v3 client
*/

@@ -265,3 +292,2 @@ captureAWSv3Client<T>(service: T): T;

*
* @decorator Class
* @param options - (_optional_) Options for the decorator

@@ -303,3 +329,2 @@ */

*
* @decorator Class
* @param options - (_optional_) Options for the decorator

@@ -338,4 +363,2 @@ */

* ```
*
* @returns string - The root X-Ray trace id.
*/

@@ -362,4 +385,2 @@ getRootXrayTraceId(): string | undefined;

* ```
*
* @returns The active segment or subsegment in the current scope. Will log a warning and return `undefined` if no segment is found.
*/

@@ -373,4 +394,2 @@ getSegment(): Segment | Subsegment | undefined;

* @see https://docs.aws.amazon.com/xray/latest/devguide/xray-concepts.html#xray-concepts-traces
*
* @returns boolean - `true` if the trace is sampled, `false` if tracing is disabled or the trace is not sampled.
*/

@@ -383,8 +402,6 @@ isTraceSampled(): boolean;

* if tracer is currently enabled.
*
* @returns tracingEnabled - `true` if tracing is enabled, `false` otherwise.
*/
isTracingEnabled(): boolean;
/**
* Adds annotation to existing segment or subsegment.
* Add annotation to existing segment or subsegment.
*

@@ -409,3 +426,3 @@ * @see https://docs.aws.amazon.com/xray/latest/devguide/xray-sdk-nodejs-segment.html#xray-sdk-nodejs-segment-annotations

/**
* Adds metadata to existing segment or subsegment.
* Add metadata to existing segment or subsegment.
*

@@ -432,3 +449,3 @@ * @see https://docs.aws.amazon.com/xray/latest/devguide/xray-sdk-nodejs-segment.html#xray-sdk-nodejs-segment-metadata

/**
* Sets the passed subsegment as the current active subsegment.
* Set the passed subsegment as the current active subsegment.
*

@@ -461,3 +478,3 @@ * If you are using a middleware or a decorator this is done automatically for you.

/**
* Getter for `envVarsService`.
* Get for `envVarsService`.
* Used internally during initialization.

@@ -482,3 +499,3 @@ */

/**
* Setter for `captureError` based on configuration passed and environment variables.
* Set `captureError` based on configuration passed and environment variables.
* Used internally during initialization.

@@ -496,7 +513,6 @@ */

* @param enabled - Whether or not to patch all HTTP clients
* @returns void
*/
private setCaptureHTTPsRequests;
/**
* Setter for `captureResponse` based on configuration passed and environment variables.
* Set `captureResponse` based on configuration passed and environment variables.
* Used internally during initialization.

@@ -506,3 +522,3 @@ */

/**
* Setter for `customConfigService` based on configuration passed.
* Set `customConfigService` based on configuration passed.
* Used internally during initialization.

@@ -514,3 +530,3 @@ *

/**
* Setter and initializer for `envVarsService`.
* Set and initialize `envVarsService`.
* Used internally during initialization.

@@ -527,3 +543,3 @@ */

/**
* Setter for `customConfigService` based on configurations passed and environment variables.
* Set `customConfigService` based on configurations passed and environment variables.
* Used internally during initialization.

@@ -535,3 +551,3 @@ *

/**
* Setter for `tracingEnabled` based on configurations passed and environment variables.
* Set `tracingEnabled` based on configurations passed and environment variables.
* Used internally during initialization.

@@ -538,0 +554,0 @@ *

@@ -0,1 +1,11 @@

/**
* If the AWS_XRAY_CONTEXT_MISSING environment variable is not set, we set it to IGNORE_ERROR.
*
* This is to prevent the AWS X-Ray SDK from logging errors when using top-level await features that make HTTP requests.
* For example, when using the Parameters utility to fetch parameters during the initialization of the Lambda handler - See #2046
*/
if (process.env.AWS_XRAY_CONTEXT_MISSING === '' ||
process.env.AWS_XRAY_CONTEXT_MISSING === undefined) {
process.env.AWS_XRAY_CONTEXT_MISSING = 'IGNORE_ERROR';
}
import { Utility } from '@aws-lambda-powertools/commons';

@@ -25,3 +35,3 @@ import xraySdk from 'aws-xray-sdk-core';

*
* If you use function-based Lambda handlers you can use the [captureLambdaHandler()](./_aws_lambda_powertools_tracer.Tracer.html) middy middleware to automatically:
* If you use function-based Lambda handlers you can use the {@link Tracer.captureLambdaHandler} middy middleware to automatically:
* * handle the subsegment lifecycle

@@ -49,3 +59,3 @@ * * add the `ServiceName` and `ColdStart` annotations

*
* If instead you use TypeScript Classes to wrap your Lambda handler you can use the [@tracer.captureLambdaHandler()](./_aws_lambda_powertools_tracer.Tracer.html#captureLambdaHandler) decorator to automatically:
* If instead you use TypeScript Classes to wrap your Lambda handler you can use the {@link Tracer.captureLambdaHandler} decorator to automatically:
* * handle the subsegment lifecycle

@@ -115,11 +125,41 @@ * * add the `ServiceName` and `ColdStart` annotations

class Tracer extends Utility {
/**
* The provider service interface used by the Tracer.
* This interface defines the methods and properties that a provider service must implement.
*/
provider;
/**
* Flag indicating whether to capture errors.
* This is used to determine if errors should be added to the trace as metadata.
*
* @default true
*/
captureError = true;
/**
* Flag indicating whether to capture HTTP(s) requests.
* @default true
*/
captureHTTPsRequests = true;
/**
* Flag indicating whether to capture response data.
* @default true
*/
captureResponse = true;
/**
* The custom configuration service used by the Tracer.
*/
customConfigService;
// envVarsService is always initialized in the constructor in setOptions()
/**
* The environment variables service used by the Tracer, is always initialized in the constructor in setOptions().
*/
envVarsService;
// serviceName is always initialized in the constructor in setOptions()
/**
* The name of the service, is always initialized in the constructor in setOptions().
*/
serviceName;
/**
* Flag indicating whether tracing is enabled.
* @default true
*/
tracingEnabled = true;

@@ -179,3 +219,2 @@ constructor(options = {}) {

* Add service name to the current segment or subsegment as annotation.
*
*/

@@ -223,3 +262,2 @@ addServiceNameAnnotation() {

* @param aws - AWS SDK v2 import
* @returns AWS - Instrumented AWS SDK
*/

@@ -252,3 +290,2 @@ captureAWS(aws) {

* @param service - AWS SDK v2 client
* @returns service - Instrumented AWS SDK v2 client
*/

@@ -296,3 +333,2 @@ captureAWSClient(service) {

* @param service - AWS SDK v3 client
* @returns service - Instrumented AWS SDK v3 client
*/

@@ -334,3 +370,2 @@ captureAWSv3Client(service) {

*
* @decorator Class
* @param options - (_optional_) Options for the decorator

@@ -414,3 +449,2 @@ */

*
* @decorator Class
* @param options - (_optional_) Options for the decorator

@@ -490,4 +524,2 @@ */

* ```
*
* @returns string - The root X-Ray trace id.
*/

@@ -516,4 +548,2 @@ getRootXrayTraceId() {

* ```
*
* @returns The active segment or subsegment in the current scope. Will log a warning and return `undefined` if no segment is found.
*/

@@ -536,4 +566,2 @@ getSegment() {

* @see https://docs.aws.amazon.com/xray/latest/devguide/xray-concepts.html#xray-concepts-traces
*
* @returns boolean - `true` if the trace is sampled, `false` if tracing is disabled or the trace is not sampled.
*/

@@ -550,4 +578,2 @@ isTraceSampled() {

* if tracer is currently enabled.
*
* @returns tracingEnabled - `true` if tracing is enabled, `false` otherwise.
*/

@@ -558,3 +584,3 @@ isTracingEnabled() {

/**
* Adds annotation to existing segment or subsegment.
* Add annotation to existing segment or subsegment.
*

@@ -583,3 +609,3 @@ * @see https://docs.aws.amazon.com/xray/latest/devguide/xray-sdk-nodejs-segment.html#xray-sdk-nodejs-segment-annotations

/**
* Adds metadata to existing segment or subsegment.
* Add metadata to existing segment or subsegment.
*

@@ -610,3 +636,3 @@ * @see https://docs.aws.amazon.com/xray/latest/devguide/xray-sdk-nodejs-segment.html#xray-sdk-nodejs-segment-metadata

/**
* Sets the passed subsegment as the current active subsegment.
* Set the passed subsegment as the current active subsegment.
*

@@ -645,3 +671,3 @@ * If you are using a middleware or a decorator this is done automatically for you.

/**
* Getter for `envVarsService`.
* Get for `envVarsService`.
* Used internally during initialization.

@@ -675,3 +701,3 @@ */

/**
* Setter for `captureError` based on configuration passed and environment variables.
* Set `captureError` based on configuration passed and environment variables.
* Used internally during initialization.

@@ -701,3 +727,2 @@ */

* @param enabled - Whether or not to patch all HTTP clients
* @returns void
*/

@@ -722,3 +747,3 @@ setCaptureHTTPsRequests(enabled) {

/**
* Setter for `captureResponse` based on configuration passed and environment variables.
* Set `captureResponse` based on configuration passed and environment variables.
* Used internally during initialization.

@@ -740,3 +765,3 @@ */

/**
* Setter for `customConfigService` based on configuration passed.
* Set `customConfigService` based on configuration passed.
* Used internally during initialization.

@@ -752,3 +777,3 @@ *

/**
* Setter and initializer for `envVarsService`.
* Set and initialize `envVarsService`.
* Used internally during initialization.

@@ -777,3 +802,3 @@ */

/**
* Setter for `customConfigService` based on configurations passed and environment variables.
* Set `customConfigService` based on configurations passed and environment variables.
* Used internally during initialization.

@@ -802,3 +827,3 @@ *

/**
* Setter for `tracingEnabled` based on configurations passed and environment variables.
* Set `tracingEnabled` based on configurations passed and environment variables.
* Used internally during initialization.

@@ -805,0 +830,0 @@ *

{
"name": "@aws-lambda-powertools/tracer",
"version": "2.7.0",
"version": "2.8.0",
"description": "The tracer package for the Powertools for AWS Lambda (TypeScript) library",

@@ -28,4 +28,4 @@ "author": {

"dependencies": {
"@aws-lambda-powertools/commons": "^2.7.0",
"aws-xray-sdk-core": "^3.9.0"
"@aws-lambda-powertools/commons": "^2.8.0",
"aws-xray-sdk-core": "^3.10.0"
},

@@ -32,0 +32,0 @@ "peerDependencies": {

@@ -7,13 +7,7 @@ # Powertools for AWS Lambda (TypeScript) <!-- omit in toc -->

> Also available in [Python](https://github.com/aws-powertools/powertools-lambda-python), [Java](https://github.com/aws-powertools/powertools-lambda-java), and [.NET](https://github.com/aws-powertools/powertools-lambda-dotnet).
**[Documentation](https://docs.powertools.aws.dev/lambda/typescript/)** | **[npm](https://www.npmjs.com/org/aws-lambda-powertools)** | **[Roadmap](https://docs.powertools.aws.dev/lambda/typescript/latest/roadmap)** | **[Examples](https://github.com/aws-powertools/powertools-lambda-typescript/tree/main/examples)** | **[Serverless TypeScript Demo](https://github.com/aws-samples/serverless-typescript-demo)**
## Table of contents <!-- omit in toc -->
- [Features](#features)
- [Getting started](#getting-started)
- [Installation](#installation)
- [Examples](#examples)
- [Demo applications](#demo-applications)
- [Intro](#intro)
- [Usage](#usage)
- [Basic usage](#basic-usage)
- [Capture AWS SDK clients](#capture-aws-sdk-clients)
- [Add metadata and annotations](#add-metadata-and-annotations)
- [Contribute](#contribute)

@@ -26,51 +20,106 @@ - [Roadmap](#roadmap)

- [Using Lambda Layer](#using-lambda-layer)
- [Credits](#credits)
- [License](#license)
## Features
## Intro
- **[Tracer](https://docs.powertools.aws.dev/lambda/typescript/latest/core/tracer/)** - Utilities to trace Lambda function handlers, and both synchronous and asynchronous functions
- **[Logger](https://docs.powertools.aws.dev/lambda/typescript/latest/core/logger/)** - Structured logging made easier, and a middleware to enrich log items with key details of the Lambda context
- **[Metrics](https://docs.powertools.aws.dev/lambda/typescript/latest/core/metrics/)** - Custom Metrics created asynchronously via CloudWatch Embedded Metric Format (EMF)
- **[Parameters](https://docs.powertools.aws.dev/lambda/typescript/latest/utilities/parameters/)** - High-level functions to retrieve one or more parameters from AWS SSM, Secrets Manager, AppConfig, and DynamoDB
The Tracer utility is an opinionated thin wrapper for [AWS X-Ray SDK for Node.js](https://github.com/aws/aws-xray-sdk-node), to automatically capture cold starts, trace HTTP(S) clients including `fetch` and generate segments and add metadata or annotations to traces.
## Getting started
## Usage
Find the complete project's [documentation here](https://docs.powertools.aws.dev/lambda/typescript).
To get started, install the library by running:
### Installation
```sh
npm i @aws-lambda-powertools/tracer
```
The Powertools for AWS Lambda (TypeScript) utilities follow a modular approach, similar to the official [AWS SDK v3 for JavaScript](https://github.com/aws/aws-sdk-js-v3).
Each TypeScript utility is installed as standalone NPM package.
### Basic usage
Install all three core utilities at once with this single command:
Add `Tracer` to your Lambda handler as decorator:
```shell
npm install @aws-lambda-powertools/logger @aws-lambda-powertools/tracer @aws-lambda-powertools/metrics
```ts
import type { LambdaInterface } from '@aws-lambda-powertools/commons/types';
import { Tracer } from '@aws-lambda-powertools/tracer';
const tracer = new Tracer({ serviceName: 'serverlessAirline' });
class Lambda implements LambdaInterface {
// Decorate your handler class method
@tracer.captureLambdaHandler()
public async handler(_event: unknown, _context: unknown): Promise<void> {
tracer.getSegment();
}
}
const handlerClass = new Lambda();
export const handler = handlerClass.handler.bind(handlerClass);
```
Or refer to the installation guide of each utility:
or using middy:
πŸ‘‰ [Installation guide for the **Tracer** utility](https://docs.powertools.aws.dev/lambda/typescript/latest/core/tracer#getting-started)
```ts
import { Tracer } from '@aws-lambda-powertools/tracer';
import { captureLambdaHandler } from '@aws-lambda-powertools/tracer/middleware';
import middy from '@middy/core';
πŸ‘‰ [Installation guide for the **Logger** utility](https://docs.powertools.aws.dev/lambda/typescript/latest/core/logger#getting-started)
const tracer = new Tracer({ serviceName: 'serverlessAirline' });
πŸ‘‰ [Installation guide for the **Metrics** utility](https://docs.powertools.aws.dev/lambda/typescript/latest/core/metrics#getting-started)
const lambdaHandler = async (
_event: unknown,
_context: unknown
): Promise<void> => {
tracer.putAnnotation('successfulBooking', true);
};
πŸ‘‰ [Installation guide for the **Parameters** utility](https://docs.powertools.aws.dev/lambda/typescript/latest/utilities/parameters/#getting-started)
// Wrap the handler with middy
export const handler = middy(lambdaHandler)
// Use the middleware by passing the Tracer instance as a parameter
.use(captureLambdaHandler(tracer));
```
### Examples
### Capture AWS SDK clients
You can find examples of how to use Powertools for AWS Lambda (TypeScript) in the [examples](https://github.com/aws-powertools/powertools-lambda-typescript/tree/main/examples/app) directory. The application is a simple REST API that can be deployed via either AWS CDK or AWS SAM.
To capture AWS SDK clients, you can use the `captureAWSv3Client` method:
### Demo applications
```ts
import { Tracer } from '@aws-lambda-powertools/tracer';
import { SecretsManagerClient } from '@aws-sdk/client-secrets-manager';
The [Serverless TypeScript Demo](https://github.com/aws-samples/serverless-typescript-demo) shows how to use Powertools for AWS Lambda (TypeScript).
You can find instructions on how to deploy and load test this application in the [repository](https://github.com/aws-samples/serverless-typescript-demo).
const tracer = new Tracer({ serviceName: 'serverlessAirline' });
// Instrument the AWS SDK client
const client = tracer.captureAWSv3Client(new SecretsManagerClient({}));
The [AWS Lambda performance tuning](https://github.com/aws-samples/optimizations-for-lambda-functions) repository also uses Powertools for AWS Lambda (TypeScript) as well as demonstrating other performance tuning techniques for Lambda functions written in TypeScript.
export default client;
```
### Add metadata and annotations
You can add metadata and annotations to trace:
```ts
import { Tracer } from '@aws-lambda-powertools/tracer';
const tracer = new Tracer({ serviceName: 'serverlessAirline' });
export const handler = async (
_event: unknown,
_context: unknown
): Promise<void> => {
const handlerSegment = tracer.getSegment()?.addNewSubsegment('### handler');
handlerSegment && tracer.setSegment(handlerSegment);
tracer.putMetadata('paymentResponse', {
foo: 'bar',
});
tracer.putAnnotation('successfulBooking', true);
handlerSegment?.close();
handlerSegment && tracer.setSegment(handlerSegment?.parent);
};
```
## Contribute
If you are interested in contributing to this project, please refer to our [Contributing Guidelines](https://github.com/aws-powertools/powertools-lambda-typescript/blob/main/CONTRIBUTING.md).
If you are interested in contributing to this project, please refer to
our [Contributing Guidelines](https://github.com/aws-powertools/powertools-lambda-typescript/blob/main/CONTRIBUTING.md).

@@ -80,3 +129,6 @@ ## Roadmap

The roadmap of Powertools for AWS Lambda (TypeScript) is driven by customers’ demand.
Help us prioritize upcoming functionalities or utilities by [upvoting existing RFCs and feature requests](https://github.com/aws-powertools/powertools-lambda-typescript/issues), or [creating new ones](https://github.com/aws-powertools/powertools-lambda-typescript/issues/new/choose), in this GitHub repository.
Help us prioritize upcoming functionalities or utilities
by [upvoting existing RFCs and feature requests](https://github.com/aws-powertools/powertools-lambda-typescript/issues),
or [creating new ones](https://github.com/aws-powertools/powertools-lambda-typescript/issues/new/choose), in this GitHub
repository.

@@ -92,3 +144,6 @@ ## Connect

Knowing which companies are using this library is important to help prioritize the project internally. If your company is using Powertools for AWS Lambda (TypeScript), you can request to have your name and logo added to the README file by raising a [Support Powertools for AWS Lambda (TypeScript) (become a reference)](https://github.com/aws-powertools/powertools-lambda-typescript/issues/new?assignees=&labels=customer-reference&template=support_powertools.yml&title=%5BSupport+Lambda+Powertools%5D%3A+%3Cyour+organization+name%3E) issue.
Knowing which companies are using this library is important to help prioritize the project internally. If your company
is using Powertools for AWS Lambda (TypeScript), you can request to have your name and logo added to the README file by
raising a [Support Powertools for AWS Lambda (TypeScript) (become a reference)](https://s12d.com/become-reference-pt-ts)
issue.

@@ -115,14 +170,15 @@ The following companies, among others, use Powertools:

Share what you did with Powertools for AWS Lambda (TypeScript) πŸ’žπŸ’ž. Blog post, workshops, presentation, sample apps and others. Check out what the community has already shared about Powertools for AWS Lambda (TypeScript) [here](https://docs.powertools.aws.dev/lambda/typescript/latest/we_made_this).
Share what you did with Powertools for AWS Lambda (TypeScript) πŸ’žπŸ’ž. Blog post, workshops, presentation, sample apps and
others. Check out what the community has already shared about Powertools for AWS Lambda (
TypeScript) [here](https://docs.powertools.aws.dev/lambda/typescript/latest/we_made_this).
### Using Lambda Layer
This helps us understand who uses Powertools for AWS Lambda (TypeScript) in a non-intrusive way, and helps us gain future investments for other Powertools for AWS Lambda languages. When [using Layers](#lambda-layers), you can add Powertools for AWS Lambda (TypeScript) as a dev dependency (or as part of your virtual env) to not impact the development process.
This helps us understand who uses Powertools for AWS Lambda (TypeScript) in a non-intrusive way, and helps us gain
future investments for other Powertools for AWS Lambda languages.
When [using Layers](https://docs.powertools.aws.dev/lambda/typescript/latest/#lambda-layer), you can add Powertools as a
dev dependency to not impact the development process.
## Credits
Credits for the Powertools for AWS Lambda (TypeScript) idea go to [DAZN](https://github.com/getndazn) and their [DAZN Lambda Powertools](https://github.com/getndazn/dazn-lambda-powertools/).
## License
This library is licensed under the MIT-0 License. See the LICENSE file.

Sorry, the diff of this file is not supported yet

Sorry, the diff of this file is not supported yet

Sorry, the diff of this file is not supported yet

Sorry, the diff of this file is not supported yet

Sorry, the diff of this file is not supported yet

Sorry, the diff of this file is not supported yet