powertools-lambda-typescript icon indicating copy to clipboard operation
powertools-lambda-typescript copied to clipboard

Feature request: Add Event Handler Tracer Middleware

Open svozza opened this issue 3 weeks ago • 0 comments

Use case

We should have a way of getting traces from HTTP routes in event handler so that the customer does not have to manually instrument their routes.

Solution/User Experience

We could create a middleware that behaves similarly to the Middy tracer middlware we currently have. A sample implementation could look like this:

export const tracerMiddleware = (tracer: Tracer, options?: {captureResponse?: boolean}): Middleware => {
    const {captureResponse = true} = options ?? {};
    
    return async ({ reqCtx, next }) => {
        const url = new URL(reqCtx.req.url);
        const subsegment = tracer.getSegment()?.addNewSubsegment(url.pathname);
        subsegment && tracer.setSegment(subsegment);
        tracer.annotateColdStart();
        tracer.addServiceNameAnnotation();
        try {
            await next();
        } catch(err) {
            tracer.addErrorAsMetadata(err as Error);
            subsegment?.close();
            subsegment && tracer.setSegment(subsegment.parent);
            throw err;
        }
        if(captureResponse && reqCtx.res.headers.get('Content-Type') === 'application/json') {
            const responseBody = await reqCtx.res.clone().json() ?? {};
            tracer.addResponseAsMetadata(responseBody);
        }
        subsegment?.close();
        subsegment && tracer.setSegment(subsegment.parent);
    }
}

Open questions:

  1. Should the middleware take multiple tracer instances like our Middy one does?
  2. Should the logic around capturing responses be more complex, i.e., should we disallow it when we are in streaming mode? This would require us to add data to reqCtx to indicate when we are in HTTP streaming mode.

Alternative solutions

We could tell users to use the Middy tracer middleware.

Acknowledgment

Future readers

Please react with 👍 and your use case to help us understand customer demand.

svozza avatar Nov 27 '25 11:11 svozza