Log requests
This commit is contained in:
parent
1b4bb1d2e2
commit
019d1d2e62
45
src/hooks.server.ts
Normal file
45
src/hooks.server.ts
Normal file
@ -0,0 +1,45 @@
|
|||||||
|
import { log, timedExecution } from '$lib';
|
||||||
|
import { validate, v7 as uuidv7 } from 'uuid';
|
||||||
|
|
||||||
|
const requestIdHeader = 'x-request-id';
|
||||||
|
|
||||||
|
/** @type {import('@sveltejs/kit').Handle} */
|
||||||
|
export async function handle({ event, resolve }) {
|
||||||
|
// use incomming requestId, if it is a valid uuid, else generate one
|
||||||
|
const reqIdFromRequest = event.request.headers.get(requestIdHeader);
|
||||||
|
const { requestId, fromRequest } =
|
||||||
|
reqIdFromRequest && validate(reqIdFromRequest)
|
||||||
|
? { requestId: reqIdFromRequest, fromRequest: true }
|
||||||
|
: { requestId: uuidv7(), fromRequest: false };
|
||||||
|
|
||||||
|
var context = {
|
||||||
|
requestId,
|
||||||
|
route: event.route.id,
|
||||||
|
method: event.request.method,
|
||||||
|
userAgent: event.request.headers.get('user-agent'),
|
||||||
|
clientIP: event.getClientAddress()
|
||||||
|
};
|
||||||
|
if (fromRequest) {
|
||||||
|
log.trace(context, 'using incomming request-id');
|
||||||
|
}
|
||||||
|
|
||||||
|
// make requestId available to handlers
|
||||||
|
event.locals.requestId = requestId;
|
||||||
|
|
||||||
|
const { executionTime, result: response } = await timedExecution(async () => {
|
||||||
|
return await resolve(event);
|
||||||
|
});
|
||||||
|
response.headers.set(requestIdHeader, requestId);
|
||||||
|
|
||||||
|
log.info(
|
||||||
|
{
|
||||||
|
executionTime: `${executionTime}ms`,
|
||||||
|
status: response.status,
|
||||||
|
size: response.headers.get('content-length'),
|
||||||
|
...context
|
||||||
|
},
|
||||||
|
'finished request'
|
||||||
|
);
|
||||||
|
|
||||||
|
return response;
|
||||||
|
}
|
Reference in New Issue
Block a user