-
Notifications
You must be signed in to change notification settings - Fork 32
feat: log api requests #2889
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
Draft
cqnykamp
wants to merge
11
commits into
Doenet:main
Choose a base branch
from
cqnykamp:feature/logging
base: main
Could not load branches
Branch not found: {{ refName }}
Loading
Could not load tags
Nothing to show
Loading
Are you sure you want to change the base?
Some commits from the old base branch may be removed from the timeline,
and old review comments may become outdated.
Draft
feat: log api requests #2889
Changes from 2 commits
Commits
Show all changes
11 commits
Select commit
Hold shift + click to select a range
1c3b1a0
feat: log start and end of api requests
cqnykamp 997b95e
better log levels
cqnykamp 8a79b04
tweak `npm run dev`
cqnykamp 3d16709
chore: cleaner npm run dev
cqnykamp 0df1046
feat: use `pino-pretty` for dev logs
cqnykamp f542bf8
log userId for authenticated endpoints
cqnykamp 6e281b5
remove sensitive or noisy headers
cqnykamp 4b1519d
less noisy `npm run dev`
cqnykamp 49edc2a
update pretty logging
cqnykamp 95a07ec
update env vars for prod and dev3
cqnykamp fb6e4ab
use pretty flag explicitly
cqnykamp 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
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 |
|---|---|---|
| @@ -0,0 +1,88 @@ | ||
| import type { NextFunction, Request, Response } from "express"; | ||
| import pinoHttp from "pino-http"; | ||
|
|
||
| type LoggableObject = Record<string, unknown>; | ||
| type RequestLoggerOptions = { | ||
| stream?: NodeJS.WritableStream; | ||
| }; | ||
|
|
||
| /** | ||
| * Initialize the pino-http middleware for logging API requests. | ||
| * | ||
| * The middleware logs two events per API call | ||
| * 1) a start event as soon as a request enters the API (level: debug) | ||
| * 2) a completion event when the response ends (level: info) | ||
| * | ||
| * Each log entry includes only the metadata fields we want. No sensitive data. | ||
| */ | ||
| export function initRequestLogger(options: RequestLoggerOptions = {}) { | ||
| const httpLogger = pinoHttp({ | ||
| customErrorMessage() { | ||
| return "API request completed"; | ||
| }, | ||
| customErrorObject(req, res, _err, loggableObject) { | ||
| return getRequestEndObject( | ||
| req as Request, | ||
| res as Response, | ||
| loggableObject as LoggableObject, | ||
| ); | ||
| }, | ||
| customSuccessMessage() { | ||
| return "API request completed"; | ||
| }, | ||
| customSuccessObject(req, res, loggableObject) { | ||
| return getRequestEndObject( | ||
| req as Request, | ||
| res as Response, | ||
| loggableObject as LoggableObject, | ||
| ); | ||
| }, | ||
| level: "debug", | ||
| quietReqLogger: true, | ||
| stream: options.stream, | ||
| useLevel: "info", | ||
| }); | ||
|
|
||
| return (req: Request, res: Response, next: NextFunction) => { | ||
| httpLogger(req, res); | ||
| req.log.debug( | ||
| { | ||
| ...getRequestMetadata(req), | ||
| event: "request_start", | ||
| }, | ||
| "API request started", | ||
| ); | ||
| next(); | ||
| }; | ||
| } | ||
|
|
||
| /** | ||
| * Pulls the safe request fields that we want to include in every lifecycle log. | ||
| */ | ||
| function getRequestMetadata(req: Request) { | ||
| return { | ||
| anonymous: req.user?.isAnonymous ?? false, | ||
| authenticated: req.user !== undefined, | ||
| method: req.method, | ||
| path: req.originalUrl || req.url, | ||
|
cqnykamp marked this conversation as resolved.
Outdated
|
||
| }; | ||
| } | ||
|
|
||
| function getDurationMs(loggableObject: LoggableObject) { | ||
| const responseTime = loggableObject.responseTime; | ||
|
|
||
| return typeof responseTime === "number" ? responseTime : undefined; | ||
| } | ||
|
|
||
| function getRequestEndObject( | ||
| req: Request, | ||
| res: Response, | ||
| loggableObject: LoggableObject, | ||
| ) { | ||
| return { | ||
| ...getRequestMetadata(req), | ||
| durationMs: getDurationMs(loggableObject), | ||
| event: "request_end", | ||
| statusCode: res.statusCode, | ||
| }; | ||
| } | ||
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,107 @@ | ||
| import { EventEmitter } from "node:events"; | ||
| import { Writable } from "node:stream"; | ||
| import type { Request, Response } from "express"; | ||
| import { describe, expect, test } from "vitest"; | ||
| import { initRequestLogger } from "../middleware/requestLogger"; | ||
|
|
||
| class MockResponse extends EventEmitter { | ||
| statusCode = 200; | ||
| writableEnded = false; | ||
| } | ||
|
|
||
| function createMockRequest(overrides: Partial<Request> = {}) { | ||
| return { | ||
| method: "GET", | ||
| originalUrl: "/api/health", | ||
| url: "/api/health", | ||
| ...overrides, | ||
| } as Request; | ||
| } | ||
|
|
||
| function createLogCapture() { | ||
| const lines: string[] = []; | ||
| const stream = new Writable({ | ||
| write(chunk, _encoding, callback) { | ||
| lines.push(chunk.toString()); | ||
| callback(); | ||
| }, | ||
| }); | ||
|
|
||
| return { lines, stream }; | ||
| } | ||
|
|
||
| function parseLogs(lines: string[]) { | ||
| return lines.map((line) => JSON.parse(line)); | ||
| } | ||
|
|
||
| describe("initRequestLogger", () => { | ||
| test("logs request start at debug and request end at info", () => { | ||
| const { lines, stream } = createLogCapture(); | ||
| const middleware = initRequestLogger({ stream }); | ||
| const req = createMockRequest(); | ||
| const mockResponse = new MockResponse(); | ||
| const res = mockResponse as unknown as Response; | ||
|
|
||
| middleware(req, res, () => {}); | ||
|
|
||
| mockResponse.statusCode = 204; | ||
| mockResponse.writableEnded = true; | ||
| mockResponse.emit("finish"); | ||
|
|
||
| const [startLog, endLog] = parseLogs(lines); | ||
|
|
||
| expect(startLog).toMatchObject({ | ||
| anonymous: false, | ||
| authenticated: false, | ||
| event: "request_start", | ||
| level: 20, | ||
| method: "GET", | ||
| msg: "API request started", | ||
| path: "/api/health", | ||
| }); | ||
| expect(endLog).toMatchObject({ | ||
| event: "request_end", | ||
| level: 30, | ||
| msg: "API request completed", | ||
| statusCode: 204, | ||
| }); | ||
| expect(endLog.durationMs).toBeGreaterThanOrEqual(0); | ||
| }); | ||
|
|
||
| test("includes safe authenticated request metadata in both lifecycle logs", () => { | ||
| const { lines, stream } = createLogCapture(); | ||
| const middleware = initRequestLogger({ stream }); | ||
| const req = createMockRequest({ | ||
| method: "POST", | ||
| originalUrl: "/api/login/anonymous", | ||
| url: "/api/login/anonymous", | ||
| user: { isAnonymous: true } as Request["user"], | ||
| }); | ||
| const mockResponse = new MockResponse(); | ||
| const res = mockResponse as unknown as Response; | ||
|
|
||
| middleware(req, res, () => {}); | ||
|
|
||
| mockResponse.statusCode = 200; | ||
| mockResponse.writableEnded = true; | ||
| mockResponse.emit("finish"); | ||
|
|
||
| const [startLog, endLog] = parseLogs(lines); | ||
|
|
||
| expect(startLog).toMatchObject({ | ||
| anonymous: true, | ||
| authenticated: true, | ||
| event: "request_start", | ||
| method: "POST", | ||
| path: "/api/login/anonymous", | ||
| }); | ||
| expect(endLog).toMatchObject({ | ||
| anonymous: true, | ||
| authenticated: true, | ||
| event: "request_end", | ||
| method: "POST", | ||
| path: "/api/login/anonymous", | ||
| statusCode: 200, | ||
| }); | ||
| }); | ||
| }); |
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.