Skip to content

Commit 64a0b0f

Browse files
authored
Add logging for request duration and response details in 2c (#3583)
Co-authored-by: Nicolas Dorseuil <nicolas@gitbook.io>
1 parent 13ff22b commit 64a0b0f

File tree

1 file changed

+36
-1
lines changed

1 file changed

+36
-1
lines changed

packages/gitbook/openNext/customWorkers/middleware.js

Lines changed: 36 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -7,12 +7,37 @@ export { DOQueueHandler } from '../../.open-next/.build/durable-objects/queue.js
77

88
export { DOShardedTagCache } from '../../.open-next/.build/durable-objects/sharded-tag-cache.js';
99

10+
//Format used by the tail logger
11+
const formatLog = (requestDuration, responseCode, responseCache, responseRoute) =>
12+
`%${JSON.stringify({ requestDuration, responseCode, responseCache, responseRoute })}%[main] Response Done`;
13+
14+
const getResolvedRoute = (reqOrResp, defaultValue) => {
15+
try {
16+
const resolvedRoutes = JSON.parse(
17+
reqOrResp.headers.get('x-opennext-resolved-routes') ?? ''
18+
)[0].route;
19+
return resolvedRoutes ?? defaultValue;
20+
} catch {
21+
return defaultValue;
22+
}
23+
};
24+
1025
export default class extends WorkerEntrypoint {
1126
async fetch(request) {
1227
return runWithCloudflareRequestContext(request, this.env, this.ctx, async () => {
28+
const startTime = Date.now();
1329
// - `Request`s are handled by the Next server
1430
const reqOrResp = await middlewareHandler(request, this.env, this.ctx);
1531
if (reqOrResp instanceof Response) {
32+
const duration = Date.now() - startTime;
33+
const logMessage = formatLog(
34+
duration,
35+
reqOrResp.status,
36+
reqOrResp.headers.get('x-opennext-cache') ?? 'MISS',
37+
getResolvedRoute(reqOrResp, 'middleware')
38+
);
39+
// biome-ignore lint/suspicious/noConsole: <explanation>
40+
console.log(logMessage);
1641
return reqOrResp;
1742
}
1843

@@ -22,12 +47,22 @@ export default class extends WorkerEntrypoint {
2247
'Cloudflare-Workers-Version-Overrides',
2348
`gitbook-open-v2-${this.env.STAGE}="${this.env.WORKER_VERSION_ID}"`
2449
);
25-
return this.env.DEFAULT_WORKER?.fetch(reqOrResp, {
50+
const response = await this.env.DEFAULT_WORKER?.fetch(reqOrResp, {
2651
redirect: 'manual',
2752
cf: {
2853
cacheEverything: false,
2954
},
3055
});
56+
const formatedLog = formatLog(
57+
Date.now() - startTime,
58+
response.status,
59+
`SERVER-${response.headers.get('x-nextjs-cache') ?? 'MISS'}`,
60+
getResolvedRoute(reqOrResp, 'unresolved')
61+
);
62+
// biome-ignore lint/suspicious/noConsole: <explanation>
63+
console.log(formatedLog);
64+
65+
return response;
3166
}
3267
// If we are in preview mode, we need to send the request to the preview URL
3368
const modifiedUrl = new URL(reqOrResp.url);

0 commit comments

Comments
 (0)