Skip to content

Commit 1659704

Browse files
committed
feat: added captureHTTPsRequest feature
1 parent 4941a34 commit 1659704

16 files changed

+333
-43
lines changed

Diff for: docs/core/tracer.md

+64-11
Original file line numberDiff line numberDiff line change
@@ -16,6 +16,7 @@ Tracer is an opinionated thin wrapper for [AWS X-Ray SDK for Node.js](https://gi
1616

1717
* Auto capture cold start and service name as annotations, and responses or full exceptions as metadata
1818
* Auto-disable when not running in AWS Lambda environment
19+
* Automatically trace HTTP(s) clients and generate segments for each request
1920
* Support tracing functions via decorators, middleware, and manual instrumentation
2021
* Support tracing AWS SDK v2 and v3 via AWS X-Ray SDK for Node.js
2122

@@ -49,13 +50,13 @@ The `Tracer` utility must always be instantiated outside of the Lambda handler.
4950

5051
### Utility settings
5152

52-
The library has one optional setting. You can set it as environment variable, or pass it in the constructor.
53-
54-
This setting will be used across all traces emitted:
53+
The library has three optional settings. You can set them as environment variables, or pass them in the constructor:
5554

5655
Setting | Description | Environment variable | Constructor parameter
5756
------------------------------------------------- |------------------------------------------------------------------------------------------------| ------------------------------------------------- | -------------------------------------------------
57+
**Tracing enabled** | Enables or disables tracing. By default tracing is enabled when running in AWS Lambda. | `POWERTOOLS_TRACE_ENABLED` | `enabled`
5858
**Service name** | Sets an annotation with the **name of the service** across all traces e.g. `serverlessAirline` | `POWERTOOLS_SERVICE_NAME` | `serviceName`
59+
**Capture HTTPs Requests** | Defines whether HTTPs requests will be traced or not, enabled by default when tracing is also enabled. | `POWERTOOLS_TRACER_CAPTURE_HTTPS_REQUESTS` | `captureHTTPsRequests`
5960

6061
For a **complete list** of supported environment variables, refer to [this section](./../index.md#environment-variables).
6162

@@ -137,13 +138,9 @@ You can quickly start by importing the `Tracer` class, initialize it outside the
137138

138139
=== "Middy Middleware"
139140

140-
!!! tip "Using Middy for the first time?"
141-
You can install Middy by running `npm i @middy/core`.
142-
Learn more about [its usage and lifecycle in the official Middy documentation](https://github.com/middyjs/middy#usage){target="_blank"}.
143-
144141
```typescript hl_lines="1-2 11 13"
145142
import { Tracer, captureLambdaHandler } from '@aws-lambda-powertools/tracer';
146-
import middy from '@middy/core';
143+
import middy from '@middy/core'; // (1)
147144

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

@@ -157,6 +154,9 @@ You can quickly start by importing the `Tracer` class, initialize it outside the
157154
.use(captureLambdaHandler(tracer));
158155
```
159156

157+
1. Using Middy for the first time? You can install Middy by running `npm i @middy/core`.
158+
Learn more about [its usage and lifecycle in the official Middy documentation](https://github.com/middyjs/middy#usage){target="_blank"}.
159+
160160
=== "Decorator"
161161

162162
!!! info
@@ -326,13 +326,66 @@ If you're looking to shave a few microseconds, or milliseconds depending on your
326326
=== "index.ts"
327327

328328
```typescript hl_lines="5"
329-
import { S3 } from "aws-sdk";
329+
import { S3 } from 'aws-sdk';
330330
import { Tracer } from '@aws-lambda-powertools/tracer';
331331

332332
const tracer = new Tracer({ serviceName: 'serverlessAirline' });
333333
const s3 = tracer.captureAWSClient(new S3());
334334
```
335335

336+
### Tracing HTTP requests
337+
338+
When your function makes calls to microservices or public HTTP APIs, Tracer automatically traces those calls and add the API to the service graph as a downstream service.
339+
340+
You can opt-out from this feature by setting the **`POWERTOOLS_TRACER_CAPTURE_HTTPS_REQUESTS=false`** environment variable or by passing the `captureHTTPSRequests: false` option to the `Tracer` constructor.
341+
342+
!!! info
343+
The following snippet shows how to trace [axios](https://www.npmjs.com/package/axios) requests, but you can use any HTTP client library built on top of [http](https://nodejs.org/api/http.html) or [https](https://nodejs.org/api/https.html)
344+
345+
=== "index.ts"
346+
347+
```typescript hl_lines="2 7"
348+
import { Tracer } from '@aws-lambda-powertools/tracer';
349+
import axios from 'axios'; // (1)
350+
351+
const tracer = new Tracer({ serviceName: 'serverlessAirline' });
352+
353+
export const handler = async (event: any, context: Context): Promise<void> => {
354+
await axios.get('https://httpbin.org/status/200');
355+
};
356+
```
357+
358+
1. You can install the [axios](https://www.npmjs.com/package/axios) package using `npm i axios`
359+
=== "Example Raw X-Ray Trace excerpt"
360+
361+
```json hl_lines="6 9 12-21"
362+
{
363+
"id": "22883fbc730e3a0b",
364+
"name": "## index.handler",
365+
"start_time": 1647956168.22749,
366+
"end_time": 1647956169.0679862,
367+
"subsegments": [
368+
{
369+
"id": "ab82ab2b7d525d8f",
370+
"name": "httpbin.org",
371+
"start_time": 1647956168.407,
372+
"end_time": 1647956168.945,
373+
"http": {
374+
"request": {
375+
"url": "https://httpbin.org/status/200",
376+
"method": "GET"
377+
},
378+
"response": {
379+
"status": 200,
380+
"content_length": 0
381+
}
382+
},
383+
"namespace": "remote"
384+
}
385+
]
386+
}
387+
```
388+
336389
## Advanced
337390

338391
### Disabling response auto-capture
@@ -361,7 +414,7 @@ This is useful when you need a feature available in X-Ray that is not available
361414

362415
=== "index.ts"
363416

364-
```typescript hl_lines="6"
417+
```typescript hl_lines="7"
365418
import { Logger } from '@aws-lambda-powertools/logger';
366419
import { Tracer } from '@aws-lambda-powertools/tracer';
367420

@@ -379,4 +432,4 @@ Tracer is disabled by default when not running in the AWS Lambda environment - T
379432

380433
* Use annotations on key operations to slice and dice traces, create unique views, and create metrics from it via Trace Groups
381434
* Use a namespace when adding metadata to group data more easily
382-
* Annotations and metadata are added to the current subsegment opened. If you want them in a specific subsegment, [create one](https://docs.aws.amazon.com/xray/latest/devguide/xray-sdk-nodejs-subsegments.html#xray-sdk-nodejs-subsegments-lambda) via the escape hatch mechanism
435+
* Annotations and metadata are added to the currently open subsegment. If you want them in a specific subsegment, [create one](https://docs.aws.amazon.com/xray/latest/devguide/xray-sdk-nodejs-subsegments.html#xray-sdk-nodejs-subsegments-lambda) via the escape hatch mechanism

Diff for: docs/index.md

+1
Original file line numberDiff line numberDiff line change
@@ -54,6 +54,7 @@ Each TypeScript utility is installed as standalone NPM package.
5454
| **POWERTOOLS_TRACE_ENABLED** | Explicitly disables tracing | [Tracer](./core/tracer) | `true` |
5555
| **POWERTOOLS_TRACER_CAPTURE_RESPONSE** | Captures Lambda or method return as metadata. | [Tracer](./core/tracer) | `true` |
5656
| **POWERTOOLS_TRACER_CAPTURE_ERROR** | Captures Lambda or method exception as metadata. | [Tracer](./core/tracer) | `true` |
57+
| **POWERTOOLS_TRACER_CAPTURE_HTTPS_REQUESTS** | Captures HTTP(s) requests as segments. | [Tracer](./core/tracer) | `true` |
5758
| **POWERTOOLS_LOGGER_LOG_EVENT** | Logs incoming event | [Logger](./core/logger) | `false` |
5859
| **POWERTOOLS_LOGGER_SAMPLE_RATE** | Debug log sampling | [Logger](./core/logger) | `0` |
5960
| **POWERTOOLS_LOG_DEDUPLICATION_DISABLED** | Disables log deduplication filter protection to use Pytest Live Log feature | [Logger](./core/logger) | `false` |

Diff for: package-lock.json

+58-12
Some generated files are not rendered by default. Learn more about customizing how changed files appear on GitHub.

Diff for: packages/tracing/package.json

+2-1
Original file line numberDiff line numberDiff line change
@@ -32,6 +32,7 @@
3232
"devDependencies": {
3333
"@aws-sdk/client-dynamodb": "^3.52.0",
3434
"@types/promise-retry": "^1.1.3",
35+
"axios": "^0.26.1",
3536
"promise-retry": "^2.0.1"
3637
},
3738
"files": [
@@ -46,6 +47,6 @@
4647
},
4748
"dependencies": {
4849
"@aws-lambda-powertools/commons": "^0.7.1",
49-
"aws-xray-sdk-core": "^3.3.3"
50+
"aws-xray-sdk-core": "^3.3.4"
5051
}
5152
}

Diff for: packages/tracing/src/Tracer.ts

+41
Original file line numberDiff line numberDiff line change
@@ -15,6 +15,7 @@ import { Segment, Subsegment } from 'aws-xray-sdk-core';
1515
* ## Key features
1616
* * Auto capture cold start as annotation, and responses or full exceptions as metadata
1717
* * Auto-disable when not running in AWS Lambda environment
18+
* * Automatically trace HTTP(s) clients and generate segments for each request
1819
* * Support tracing functions via decorators, middleware, and manual instrumentation
1920
* * Support tracing AWS SDK v2 and v3 via AWS X-Ray SDK for Node.js
2021
*
@@ -115,6 +116,8 @@ class Tracer extends Utility implements TracerInterface {
115116
public provider: ProviderServiceInterface;
116117

117118
private captureError: boolean = true;
119+
120+
private captureHTTPsRequests: boolean = true;
118121

119122
private captureResponse: boolean = true;
120123

@@ -131,6 +134,9 @@ class Tracer extends Utility implements TracerInterface {
131134

132135
this.setOptions(options);
133136
this.provider = new ProviderService();
137+
if (this.isTracingEnabled() && this.captureHTTPsRequests) {
138+
this.provider.captureHTTPsGlobal();
139+
}
134140
if (!this.isTracingEnabled()) {
135141
// Tell x-ray-sdk to not throw an error if context is missing but tracing is disabled
136142
this.provider.setContextMissingStrategy(() => ({}));
@@ -631,6 +637,39 @@ class Tracer extends Utility implements TracerInterface {
631637
}
632638
}
633639

640+
/**
641+
* Patch an all HTTP(s) clients and create traces when your application makes calls outgoing calls.
642+
*
643+
* Calls using third-party HTTP request libraries, such as Axios, are supported as long as they use the native http
644+
* module under the hood. Support for third-party HTTP request libraries is provided on a best effort basis.
645+
*
646+
* @see https://docs.aws.amazon.com/xray/latest/devguide/xray-sdk-nodejs-httpclients.html
647+
*
648+
* @param enabled - Whether or not to patch all HTTP clients
649+
* @returns void
650+
*/
651+
private setCaptureHTTPsRequests(enabled?: boolean): void {
652+
if (enabled !== undefined && !enabled) {
653+
this.captureHTTPsRequests = false;
654+
655+
return;
656+
}
657+
658+
const customConfigValue = this.getCustomConfigService()?.getCaptureHTTPsRequests();
659+
if (customConfigValue !== undefined && customConfigValue.toLowerCase() === 'false') {
660+
this.captureHTTPsRequests = false;
661+
662+
return;
663+
}
664+
665+
const envVarsValue = this.getEnvVarsService()?.getCaptureHTTPsRequests();
666+
if (envVarsValue.toLowerCase() === 'false') {
667+
this.captureHTTPsRequests = false;
668+
669+
return;
670+
}
671+
}
672+
634673
/**
635674
* Setter for `captureResponse` based on configuration passed and environment variables.
636675
* Used internally during initialization.
@@ -679,6 +718,7 @@ class Tracer extends Utility implements TracerInterface {
679718
const {
680719
enabled,
681720
serviceName,
721+
captureHTTPsRequests,
682722
customConfigService
683723
} = options;
684724

@@ -688,6 +728,7 @@ class Tracer extends Utility implements TracerInterface {
688728
this.setCaptureResponse();
689729
this.setCaptureError();
690730
this.setServiceName(serviceName);
731+
this.setCaptureHTTPsRequests(captureHTTPsRequests);
691732

692733
return this;
693734
}

0 commit comments

Comments
 (0)