Server: Add request duration to log

pull/5064/head
Laurent Cozic 2021-06-07 16:27:09 +02:00
parent 3c41b45e8e
commit c8d7ecbf6c
2 changed files with 14 additions and 1 deletions

View File

@ -84,6 +84,14 @@ async function main() {
const app = new Koa();
// app.use(async function responseTime(ctx:AppContext, next:Function) {
// const start = Date.now();
// await next();
// const ms = Date.now() - start;
// console.info('Response time', ms)
// //ctx.set('X-Response-Time', `${ms}ms`);
// });
// Note: the order of middlewares is important. For example, ownerHandler
// loads the user, which is then used by notificationHandler. And finally
// routeHandler uses data from both previous middlewares. It would be good to

View File

@ -3,7 +3,7 @@ import { AppContext, Env } from '../utils/types';
import { isView, View } from '../services/MustacheService';
export default async function(ctx: AppContext) {
ctx.appLogger().info(`${ctx.request.method} ${ctx.path}`);
const requestStartTime = Date.now();
try {
const responseObject = await execRequest(ctx.routes, ctx);
@ -56,5 +56,10 @@ export default async function(ctx: AppContext) {
if (error.code) r.code = error.code;
ctx.response.body = r;
}
} finally {
// Technically this is not the total request duration because there are
// other middlewares but that should give a good approximation
const requestDuration = Date.now() - requestStartTime;
ctx.appLogger().info(`${ctx.request.method} ${ctx.path} (${requestDuration}ms)`);
}
}