@@ -37,13 +37,7 @@ The `Tracer` utility must always be instantiated outside of the Lambda handler.
37
37
=== "handler.ts"
38
38
39
39
```typescript hl_lines="1 3"
40
- import { Tracer } from '@aws-lambda-powertools/tracer';
41
-
42
- const tracer = new Tracer({ serviceName: 'serverlessAirline' });
43
-
44
- export const handler = async (_event, _context): Promise<void> => {
45
- // ...
46
- };
40
+ --8<-- "docs/snippets/tracer/basicUsage.ts"
47
41
```
48
42
49
43
### Utility settings
@@ -68,15 +62,7 @@ The `Tracer` utility is instantiated outside of the Lambda handler. In doing thi
68
62
=== "handler.ts"
69
63
70
64
```typescript hl_lines="1 4"
71
- import { Tracer } from '@aws-lambda-powertools/tracer';
72
-
73
- // Tracer parameter fetched from the environment variables (see template.yaml tab)
74
- const tracer = new Tracer();
75
-
76
- // You can also pass the parameter in the constructor
77
- // const tracer = new Tracer({
78
- // serviceName: 'serverlessAirline'
79
- // });
65
+ --8<-- "docs/snippets/tracer/sam.ts"
80
66
```
81
67
82
68
=== "template.yml"
@@ -104,19 +90,7 @@ You can quickly start by importing the `Tracer` class, initialize it outside the
104
90
Learn more about [its usage and lifecycle in the official Middy documentation](https://middy.js.org/docs/intro/getting-started){target="_blank"}.
105
91
106
92
```typescript hl_lines="1-2 11 13"
107
- import { Tracer, captureLambdaHandler } from '@aws-lambda-powertools/tracer';
108
- import middy from '@middy/core'; // (1)
109
-
110
- const tracer = new Tracer({ serviceName: 'serverlessAirline' });
111
-
112
- const lambdaHandler = async (_event: any, _context: any): Promise<void> => {
113
- /* ... */
114
- };
115
-
116
- // Wrap the handler with middy
117
- export const handler = middy(lambdaHandler)
118
- // Use the middleware by passing the Tracer instance as a parameter
119
- .use(captureLambdaHandler(tracer));
93
+ --8<-- "docs/snippets/tracer/middy.ts"
120
94
```
121
95
122
96
1. Using Middy for the first time? You can install Middy by running `npm i @middy/core`.
@@ -129,60 +103,15 @@ You can quickly start by importing the `Tracer` class, initialize it outside the
129
103
See the [official TypeScript documentation](https://www.typescriptlang.org/docs/handbook/decorators.html) for more details.
130
104
131
105
```typescript hl_lines="8"
132
- import { Tracer } from '@aws-lambda-powertools/tracer';
133
- import { LambdaInterface } from '@aws-lambda-powertools/commons';
134
-
135
- const tracer = new Tracer({ serviceName: 'serverlessAirline' });
136
-
137
- class Lambda implements LambdaInterface {
138
- // Decorate your handler class method
139
- @tracer.captureLambdaHandler()
140
- public async handler(_event: any, _context: any): Promise<void> {
141
- /* ... */
142
- }
143
- }
144
-
145
- const handlerClass = new Lambda();
146
- export const handler = handlerClass.handler.bind(handlerClass); // (1)
106
+ --8<-- "docs/snippets/tracer/decorator.ts"
147
107
```
148
108
149
109
1. Binding your handler method allows your handler to access `this`.
150
110
151
111
=== "Manual"
152
112
153
113
```typescript hl_lines="6 8-9 12-13 19 22 26 28"
154
- import { Tracer } from '@aws-lambda-powertools/tracer';
155
-
156
- const tracer = new Tracer({ serviceName: 'serverlessAirline' });
157
-
158
- export const handler = async (_event: any, context: any): Promise<unknown> => {
159
- const segment = tracer.getSegment(); // This is the facade segment (the one that is created by AWS Lambda)
160
- // Create subsegment for the function & set it as active
161
- const subsegment = segment.addNewSubsegment(`## ${process.env._HANDLER}`);
162
- tracer.setSegment(subsegment);
163
-
164
- // Annotate the subsegment with the cold start & serviceName
165
- tracer.annotateColdStart();
166
- tracer.addServiceNameAnnotation();
167
-
168
- let res;
169
- try {
170
- /* ... */
171
- // Add the response as metadata
172
- tracer.addResponseAsMetadata(res, process.env._HANDLER);
173
- } catch (err) {
174
- // Add the error as metadata
175
- tracer.addErrorAsMetadata(err as Error);
176
- throw err;
177
- } finally {
178
- // Close subsegment (the AWS Lambda one is closed automatically)
179
- subsegment.close();
180
- // Set back the facade segment as active again
181
- tracer.setSegment(segment);
182
- }
183
-
184
- return res;
185
- };
114
+ --8<-- "docs/snippets/tracer/manual.ts"
186
115
```
187
116
188
117
@@ -203,26 +132,13 @@ When using the `captureLambdaHandler` decorator or middleware, Tracer performs t
203
132
You can add annotations using ` putAnnotation ` method.
204
133
205
134
```typescript hl_lines="6"
206
- import { Tracer } from '@aws-lambda-powertools/tracer';
207
-
208
- const tracer = new Tracer({ serviceName: 'serverlessAirline' });
209
-
210
- export const handler = async (_event: any, _context: any): Promise<void> => {
211
- tracer.putAnnotation('successfulBooking', true);
212
- };
135
+ --8<-- "docs/snippets/tracer/putAnnotation.ts"
213
136
```
214
137
=== "Metadata"
215
138
You can add metadata using ` putMetadata ` method.
216
139
217
140
```typescript hl_lines="7"
218
- import { Tracer } from '@aws-lambda-powertools/tracer';
219
-
220
- const tracer = new Tracer({ serviceName: 'serverlessAirline' });
221
-
222
- export const handler = async (_event: any, _context: any): Promise<void> => {
223
- const res; /* ... */
224
- tracer.putMetadata('paymentResponse', res);
225
- };
141
+ --8<-- "docs/snippets/tracer/putMetadata.ts"
226
142
```
227
143
228
144
<figure >
@@ -237,26 +153,7 @@ You can trace other Class methods using the `captureMethod` decorator or any arb
237
153
=== "Decorator"
238
154
239
155
```typescript hl_lines="8"
240
- import { Tracer } from '@aws-lambda-powertools/tracer';
241
- import { LambdaInterface } from '@aws-lambda-powertools/commons';
242
-
243
- const tracer = new Tracer({ serviceName: 'serverlessAirline' });
244
-
245
- class Lambda implements LambdaInterface {
246
- // Decorate your class method
247
- @tracer.captureMethod() // (1)
248
- public getChargeId(): string {
249
- /* ... */
250
- return 'foo bar';
251
- }
252
-
253
- public async handler(_event: any, _context: any): Promise<void> {
254
- /* ... */
255
- }
256
- }
257
-
258
- const handlerClass = new Lambda();
259
- export const handler = handlerClass.handler.bind(handlerClass); // (2)
156
+ --8<-- "docs/snippets/tracer/captureMethodDecorator.ts"
260
157
```
261
158
262
159
1. You can set a custom name for the subsegment by passing `subSegmentName` to the decorator, like: `@tracer.captureMethod({ subSegmentName: '### myCustomMethod' })`.
@@ -265,40 +162,7 @@ You can trace other Class methods using the `captureMethod` decorator or any arb
265
162
=== "Manual"
266
163
267
164
```typescript hl_lines="6 8-9 15 18 23 25"
268
- import { Tracer } from '@aws-lambda-powertools/tracer';
269
-
270
- const tracer = new Tracer({ serviceName: 'serverlessAirline' });
271
-
272
- const getChargeId = async (): Promise<unknown> => {
273
- const parentSubsegment = tracer.getSegment(); // This is the subsegment currently active
274
- // Create subsegment for the function & set it as active
275
- const subsegment = parentSubsegment.addNewSubsegment(`### chargeId`);
276
- tracer.setSegment(subsegment);
277
-
278
- let res;
279
- try {
280
- /* ... */
281
- // Add the response as metadata
282
- tracer.addResponseAsMetadata(res, 'chargeId');
283
- } catch (err) {
284
- // Add the error as metadata
285
- tracer.addErrorAsMetadata(err as Error);
286
- throw err;
287
- }
288
-
289
- // Close subsegment (the AWS Lambda one is closed automatically)
290
- subsegment.close();
291
- // Set the facade segment as active again
292
- tracer.setSegment(parentSubsegment);
293
-
294
- return res;
295
- };
296
-
297
- export const handler = async (_event: any, _context: any): Promise<void> => {
298
- const chargeId = getChargeId();
299
- const payment = collectPayment(chargeId);
300
- /* ... */
301
- };
165
+ --8<-- "docs/snippets/tracer/captureMethodManual.ts"
302
166
```
303
167
304
168
@@ -314,11 +178,7 @@ You can patch any AWS SDK clients by calling the `captureAWSv3Client` method:
314
178
=== "index.ts"
315
179
316
180
```typescript hl_lines="5"
317
- import { S3Client } from '@aws-sdk/client-s3';
318
- import { Tracer } from '@aws-lambda-powertools/tracer';
319
-
320
- const tracer = new Tracer({ serviceName: 'serverlessAirline' });
321
- const client = tracer.captureAWSv3Client(new S3Client({}));
181
+ --8<-- "docs/snippets/tracer/captureAWSv3.ts"
322
182
```
323
183
324
184
!!! info
@@ -329,22 +189,15 @@ You can patch all AWS SDK v2 clients by calling the `captureAWS` method:
329
189
=== "index.ts"
330
190
331
191
```typescript hl_lines="4"
332
- import { Tracer } from '@aws-lambda-powertools/tracer';
333
-
334
- const tracer = new Tracer({ serviceName: 'serverlessAirline' });
335
- const AWS = tracer.captureAWS(require('aws-sdk'));
192
+ --8<-- "docs/snippets/tracer/captureAWSAll.ts"
336
193
```
337
194
338
195
If you're looking to shave a few microseconds, or milliseconds depending on your function memory configuration, you can patch only specific AWS SDK v2 clients using ` captureAWSClient ` :
339
196
340
197
=== "index.ts"
341
198
342
199
```typescript hl_lines="5"
343
- import { S3 } from 'aws-sdk';
344
- import { Tracer } from '@aws-lambda-powertools/tracer';
345
-
346
- const tracer = new Tracer({ serviceName: 'serverlessAirline' });
347
- const s3 = tracer.captureAWSClient(new S3());
200
+ --8<-- "docs/snippets/tracer/captureAWS.ts"
348
201
```
349
202
350
203
### Tracing HTTP requests
@@ -360,14 +213,7 @@ You can opt-out from this feature by setting the **`POWERTOOLS_TRACER_CAPTURE_HT
360
213
=== "index.ts"
361
214
362
215
```typescript hl_lines="2 7"
363
- import { Tracer } from '@aws-lambda-powertools/tracer';
364
- import axios from 'axios'; // (1)
365
-
366
- const tracer = new Tracer({ serviceName: 'serverlessAirline' });
367
-
368
- export const handler = async (event: unknown, context: Context): Promise<void> => {
369
- await axios.get('https://httpbin.org/status/200');
370
- };
216
+ --8<-- "docs/snippets/tracer/captureHTTP.ts"
371
217
```
372
218
373
219
1. You can install the [axios](https://www.npmjs.com/package/axios) package using `npm i axios`
@@ -418,62 +264,19 @@ Alternatively, use the `captureResponse: false` option in both `tracer.captureLa
418
264
=== "method.ts"
419
265
420
266
```typescript hl_lines="6"
421
- import { Tracer } from '@aws-lambda-powertools/tracer';
422
-
423
- const tracer = new Tracer({ serviceName: 'serverlessAirline' });
424
-
425
- class Lambda implements LambdaInterface {
426
- @tracer.captureMethod({ captureResult: false })
427
- public getChargeId(): string {
428
- /* ... */
429
- return 'foo bar';
430
- }
431
-
432
- public async handler(_event: any, _context: any): Promise<void> {
433
- /* ... */
434
- }
435
- }
436
-
437
- const handlerClass = new Lambda();
438
- export const handler = handlerClass.handler.bind(handlerClass);
267
+ --8<-- "docs/snippets/tracer/disableCaptureResponseMethod.ts"
439
268
```
440
269
441
270
=== "handler.ts"
442
271
443
272
```typescript hl_lines="7"
444
- import { Tracer } from '@aws-lambda-powertools/tracer';
445
- import { LambdaInterface } from '@aws-lambda-powertools/commons';
446
-
447
- const tracer = new Tracer({ serviceName: 'serverlessAirline' });
448
-
449
- class Lambda implements LambdaInterface {
450
- @tracer.captureLambdaHandler({ captureResponse: false })
451
- async handler(_event: any, _context: any): Promise<void> {
452
- /* ... */
453
- }
454
- }
455
-
456
- const handlerClass = new Lambda();
457
- export const handler = handlerClass.handler.bind(handlerClass);
273
+ --8<-- "docs/snippets/tracer/disableCaptureResponseHandler.ts"
458
274
```
459
275
460
276
=== "middy.ts"
461
277
462
278
```typescript hl_lines="14"
463
- import { Tracer, captureLambdaHandler } from '@aws-lambda-powertools/tracer';
464
- import middy from '@middy/core';
465
-
466
- const tracer = new Tracer({ serviceName: 'serverlessAirline' });
467
-
468
- const lambdaHandler = async (_event: any, _context: any): Promise<void> => {
469
- /* ... */
470
- };
471
-
472
- // Wrap the handler with middy
473
- export const handler = middy(lambdaHandler)
474
- // Use the middleware by passing the Tracer instance as a parameter,
475
- // but specify the captureResponse option as false.
476
- .use(captureLambdaHandler(tracer, { captureResponse: false }));
279
+ --8<-- "docs/snippets/tracer/disableCaptureResponseMiddy.ts"
477
280
```
478
281
479
282
### Disabling errors auto-capture
@@ -496,24 +299,7 @@ Tracer exposes a `getRootXrayTraceId()` method that allows you to retrieve the [
496
299
=== "index.ts"
497
300
498
301
```typescript hl_lines="9"
499
- import { Tracer } from '@aws-lambda-powertools/tracer';
500
-
501
- const tracer = new Tracer({ serviceName: 'serverlessAirline' });
502
-
503
- export const handler = async (event: unknown, context: Context): Promise<void> => {
504
- try {
505
- ...
506
- } catch (err) {
507
- const rootTraceId = tracer.getRootXrayTraceId();
508
-
509
- // Example of returning an error response
510
- return {
511
- statusCode: 500,
512
- body: `Internal Error - Please contact support and quote the following id: ${rootTraceId}`,
513
- headers: { '_X_AMZN_TRACE_ID': rootTraceId },
514
- };
515
- }
516
- };
302
+ --8<-- "docs/snippets/tracer/accessRootTraceId.ts"
517
303
```
518
304
519
305
### Escape hatch mechanism
@@ -525,13 +311,7 @@ This is useful when you need a feature available in X-Ray that is not available
525
311
=== "index.ts"
526
312
527
313
```typescript hl_lines="7"
528
- import { Logger } from '@aws-lambda-powertools/logger';
529
- import { Tracer } from '@aws-lambda-powertools/tracer';
530
-
531
- const serviceName = 'serverlessAirline';
532
- const logger = new Logger({ serviceName: serviceName });
533
- const tracer = new Tracer({ serviceName: serviceName });
534
- tracer.provider.setLogger(logger);
314
+ --8<-- "docs/snippets/tracer/escapeHatch.ts"
535
315
```
536
316
537
317
## Testing your code
0 commit comments