@@ -37,13 +37,7 @@ The `Tracer` utility must always be instantiated outside of the Lambda handler.
3737=== "handler.ts"
3838
3939 ```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"
4741 ```
4842
4943### Utility settings
@@ -68,15 +62,7 @@ The `Tracer` utility is instantiated outside of the Lambda handler. In doing thi
6862=== "handler.ts"
6963
7064 ```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"
8066 ```
8167
8268=== "template.yml"
@@ -104,19 +90,7 @@ You can quickly start by importing the `Tracer` class, initialize it outside the
10490 Learn more about [its usage and lifecycle in the official Middy documentation](https://middy.js.org/docs/intro/getting-started){target="_blank"}.
10591
10692 ```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"
12094 ```
12195
12296 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
129103 See the [official TypeScript documentation](https://www.typescriptlang.org/docs/handbook/decorators.html) for more details.
130104
131105 ```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"
147107 ```
148108
149109 1. Binding your handler method allows your handler to access `this`.
150110
151111=== "Manual"
152112
153113 ```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"
186115 ```
187116
188117
@@ -203,26 +132,13 @@ When using the `captureLambdaHandler` decorator or middleware, Tracer performs t
203132 You can add annotations using ` putAnnotation ` method.
204133
205134 ```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"
213136 ```
214137=== "Metadata"
215138 You can add metadata using ` putMetadata ` method.
216139
217140 ```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"
226142 ```
227143
228144<figure >
@@ -237,26 +153,7 @@ You can trace other Class methods using the `captureMethod` decorator or any arb
237153=== "Decorator"
238154
239155 ```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"
260157 ```
261158
262159 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
265162=== "Manual"
266163
267164 ```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"
302166 ```
303167
304168
@@ -314,11 +178,7 @@ You can patch any AWS SDK clients by calling the `captureAWSv3Client` method:
314178=== "index.ts"
315179
316180 ```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"
322182 ```
323183
324184!!! info
@@ -329,22 +189,15 @@ You can patch all AWS SDK v2 clients by calling the `captureAWS` method:
329189=== "index.ts"
330190
331191 ```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"
336193 ```
337194
338195If 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 ` :
339196
340197=== "index.ts"
341198
342199 ```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"
348201 ```
349202
350203### Tracing HTTP requests
@@ -360,14 +213,7 @@ You can opt-out from this feature by setting the **`POWERTOOLS_TRACER_CAPTURE_HT
360213=== "index.ts"
361214
362215 ```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"
371217 ```
372218
373219 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
418264=== "method.ts"
419265
420266 ```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"
439268 ```
440269
441270=== "handler.ts"
442271
443272 ```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"
458274 ```
459275
460276=== "middy.ts"
461277
462278 ```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"
477280 ```
478281
479282### Disabling errors auto-capture
@@ -496,24 +299,7 @@ Tracer exposes a `getRootXrayTraceId()` method that allows you to retrieve the [
496299=== "index.ts"
497300
498301 ```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"
517303 ```
518304
519305### Escape hatch mechanism
@@ -525,13 +311,7 @@ This is useful when you need a feature available in X-Ray that is not available
525311=== "index.ts"
526312
527313 ```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"
535315 ```
536316
537317## Testing your code
0 commit comments