From e3f24692a86abebb03d8d351bf36684f04f56ee5 Mon Sep 17 00:00:00 2001 From: Alex Robertson Date: Thu, 30 Jan 2020 15:15:39 -0600 Subject: [PATCH] Add koaBunyanLogger.timeContext(opts) (#41977) https://github.com/koajs/bunyan-logger#koabunyanloggertimecontextopts > koaBunyanLogger.timeContext(opts) > Adds time(label) and timeEnd(label) methods to the koa context, which records the time between the time() and timeEnd() calls for a given label. > > Calls to time() and timeEnd() can be nested or interleaved as long as they're balanced for each label. > > Options: > > logLevel: name of log level to use; defaults to 'trace' > updateLogFields: function which will be called with arguments (fields) in koa context; can update fields or return a new object. --- types/koa-bunyan-logger/index.d.ts | 6 ++++++ types/koa-bunyan-logger/koa-bunyan-logger-tests.ts | 14 ++++++++++++++ 2 files changed, 20 insertions(+) diff --git a/types/koa-bunyan-logger/index.d.ts b/types/koa-bunyan-logger/index.d.ts index 40c02a4faf..84a5cb0631 100644 --- a/types/koa-bunyan-logger/index.d.ts +++ b/types/koa-bunyan-logger/index.d.ts @@ -39,8 +39,14 @@ declare namespace koaBunyanLogger { ignorePath?: string[]; } + interface TimeContextOptions { + logLevel?: string; + updateLogFields?: (fields: any) => any; + } + function requestLogger(opts?: RequestLoggerOptions): Middleware; function requestIdContext(opts?: RequestIdContextOptions): Middleware; + function timeContext(opts?: TimeContextOptions): Middleware; } // Extend the Koa context to add the logger.. diff --git a/types/koa-bunyan-logger/koa-bunyan-logger-tests.ts b/types/koa-bunyan-logger/koa-bunyan-logger-tests.ts index 509e6759f3..739faab5f2 100644 --- a/types/koa-bunyan-logger/koa-bunyan-logger-tests.ts +++ b/types/koa-bunyan-logger/koa-bunyan-logger-tests.ts @@ -6,6 +6,20 @@ app.use(koaBunyanLogger()); app.use(koaBunyanLogger.requestIdContext()); app.use(koaBunyanLogger.requestLogger()); app.use(koaBunyanLogger.requestLogger({ ignorePath: ['/ping'] })); +app.use(koaBunyanLogger.timeContext()); +app.use( + koaBunyanLogger.timeContext({ + logLevel: 'warn', + updateLogFields(fields) { + return { + request_trace: { + name: fields.label, + time: fields.duration, + }, + }; + }, + }), +); app.use(async (ctx, next) => { ctx.log.info('Got a request from %s for %s', ctx.request.ip, ctx.path);