-
Notifications
You must be signed in to change notification settings - Fork 190
feat(event-handler): add metrics middleware for HTTP routes #5086
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
Merged
Merged
Changes from all commits
Commits
Show all changes
12 commits
Select commit
Hold shift + click to select a range
d4dbb3c
feat(event-handler): add metrics middleware for HTTP routes
svozza bae9f2d
refactor(event-handler): use fluent interface for metrics middleware
svozza 6842a81
refactor(event-handler): make RequestContext a discriminated union on…
svozza 5682cdc
feat(event-handler): add request metadata to metrics middleware
svozza 856b3ac
test(event-handler): cover undefined extendedRequestId branch in metr…
svozza d5b4549
refactor(event-handler): remove unused getResponseType function
svozza 45d68c3
docs(event-handler): update metrics middleware jsdoc with metadata de…
svozza be23e38
feat(event-handler): use sourceIp for API Gateway events, NOT_FOUND d…
svozza a5d3a64
refactor(event-handler): use null for unmatched route instead of raw …
svozza 6d8fd11
fix(event-handler): add missing route property to mock RequestContext…
svozza edceaf8
fix(event-handler): use null for route in mock RequestContext
svozza 5df691a
update lock file
svozza File filter
Filter by extension
Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
There are no files selected for viewing
Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.
Oops, something went wrong.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -1,3 +1,4 @@ | ||
| export { compress } from './compress.js'; | ||
| export { cors } from './cors.js'; | ||
| export { metrics } from './metrics.js'; | ||
| export { tracer } from './tracer.js'; |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,120 @@ | ||
| import type { Metrics } from '@aws-lambda-powertools/metrics'; | ||
| import { MetricUnit } from '@aws-lambda-powertools/metrics'; | ||
| import type { Middleware, RequestContext } from '../../types/http.js'; | ||
| import { HttpError } from '../errors.js'; | ||
|
|
||
| const getHeaderMetadata = (req: Request): Record<string, string> => { | ||
| const metadata: Record<string, string> = {}; | ||
|
|
||
| const userAgent = req.headers.get('User-Agent'); | ||
| if (userAgent) { | ||
| metadata.userAgent = userAgent; | ||
| } | ||
|
|
||
| return metadata; | ||
| }; | ||
|
|
||
| const getIpAddress = (reqCtx: RequestContext): string | undefined => { | ||
| if (reqCtx.responseType === 'ApiGatewayV1') { | ||
| return reqCtx.event.requestContext.identity.sourceIp; | ||
| } | ||
| if (reqCtx.responseType === 'ApiGatewayV2') { | ||
| return reqCtx.event.requestContext.http.sourceIp; | ||
| } | ||
| const xForwardedFor = reqCtx.req.headers.get('X-Forwarded-For'); | ||
| if (xForwardedFor) { | ||
| return xForwardedFor.split(',')[0].trim(); | ||
| } | ||
| return undefined; | ||
| }; | ||
|
|
||
| const getEventMetadata = (reqCtx: RequestContext): Record<string, string> => { | ||
| const metadata: Record<string, string> = {}; | ||
|
|
||
| const ipAddress = getIpAddress(reqCtx); | ||
| if (ipAddress) { | ||
| metadata.ipAddress = ipAddress; | ||
| } | ||
|
|
||
| if (reqCtx.responseType !== 'ALB') { | ||
| metadata.apiGwRequestId = reqCtx.event.requestContext.requestId; | ||
| metadata.apiGwApiId = reqCtx.event.requestContext.apiId; | ||
| } | ||
| if (reqCtx.responseType === 'ApiGatewayV1') { | ||
| const extendedRequestId = reqCtx.event.requestContext.extendedRequestId; | ||
| if (extendedRequestId) { | ||
| metadata.apiGwExtendedRequestId = extendedRequestId; | ||
| } | ||
| } | ||
|
|
||
| return metadata; | ||
| }; | ||
|
|
||
| /** | ||
| * A middleware for emitting per-request metrics using Powertools Metrics. | ||
| * | ||
| * This middleware automatically: | ||
| * - Adds the matched route as a metric dimension (uses `NOT_FOUND` when no route matches to prevent dimension explosion) | ||
| * - Emits `latency` (Milliseconds), `fault` (Count), and `error` (Count) metrics | ||
| * - Adds `httpMethod` and `path` metadata for all requests | ||
| * - Adds `ipAddress` and `userAgent` metadata from request headers when available | ||
| * - Adds `apiGwRequestId` and `apiGwApiId` metadata for API Gateway V1 and V2 events | ||
| * - Adds `apiGwExtendedRequestId` metadata for API Gateway V1 events when available | ||
| * - Publishes stored metrics after each request | ||
| * | ||
| * @example | ||
| * ```typescript | ||
| * import { Router } from '@aws-lambda-powertools/event-handler/http'; | ||
| * import { metrics as metricsMiddleware } from '@aws-lambda-powertools/event-handler/http/middleware/metrics'; | ||
| * import { Metrics } from '@aws-lambda-powertools/metrics'; | ||
| * | ||
| * const metrics = new Metrics({ namespace: 'my-app', serviceName: 'my-service' }); | ||
| * const app = new Router(); | ||
| * | ||
| * app.use(metricsMiddleware(metrics)); | ||
| * ``` | ||
| * | ||
| * @param metrics - The Metrics instance to use for emitting metrics | ||
| */ | ||
| const metrics = (metrics: Metrics): Middleware => { | ||
| return async ({ reqCtx, next }) => { | ||
| const start = performance.now(); | ||
| let status = 500; | ||
|
|
||
| try { | ||
| await next(); | ||
| status = reqCtx.res.status; | ||
| } catch (error) { | ||
| status = error instanceof HttpError ? error.statusCode : 500; | ||
| throw error; | ||
| } finally { | ||
| const url = new URL(reqCtx.req.url); | ||
| const metadata = { | ||
| httpMethod: reqCtx.req.method, | ||
| path: url.pathname, | ||
| statusCode: String(status), | ||
| ...getHeaderMetadata(reqCtx.req), | ||
| ...getEventMetadata(reqCtx), | ||
| }; | ||
| for (const [key, value] of Object.entries(metadata)) { | ||
| metrics.addMetadata(key, value); | ||
| } | ||
| metrics | ||
| .addDimension('route', reqCtx.route ?? 'NOT_FOUND') | ||
| .addMetric( | ||
| 'latency', | ||
| MetricUnit.Milliseconds, | ||
| performance.now() - start | ||
| ) | ||
| .addMetric('fault', MetricUnit.Count, status >= 500 ? 1 : 0) | ||
| .addMetric( | ||
| 'error', | ||
| MetricUnit.Count, | ||
| status >= 400 && status < 500 ? 1 : 0 | ||
| ) | ||
| .publishStoredMetrics(); | ||
| } | ||
| }; | ||
| }; | ||
|
|
||
| export { metrics }; |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Oops, something went wrong.
Oops, something went wrong.
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
Uh oh!
There was an error while loading. Please reload this page.