Skip to content

Commit 506edd7

Browse files
committed
fix(driver-express): requestLogger does not compute the accurate request duration as it doesn't run the logger within the finish event listener.
1 parent 3e0922c commit 506edd7

1 file changed

Lines changed: 16 additions & 13 deletions

File tree

packages/driver-express/src/middlewares/request-logger.ts

Lines changed: 16 additions & 13 deletions
Original file line numberDiff line numberDiff line change
@@ -22,26 +22,29 @@ export const requestLogger = ({
2222
allowInProduction?: boolean
2323
} = {}) => async (req: Request, res: Response, next: NextFunction) => {
2424
const VERBOSE = process.env.VERBOSITY != '0'
25-
if ((nodeEnv() === 'prod' && !allowInProduction) || !VERBOSE) return next()
26-
27-
const start = Date.now()
28-
29-
const status = res.statusCode || 200
30-
const duration = Date.now() - start
31-
Logger.log([
32-
[`[${req.method}]`, colors[req.method] || 'white'],
33-
[req.url, 'cyan'],
34-
[status.toString(), status >= 500 ? 'red' : status >= 400 ? 'yellow' : 'green'],
35-
[`- ${duration}ms`, 'dim']
36-
], ' ')
25+
const startedAt = performance.now()
26+
27+
res.once('finish', () => {
28+
if ((nodeEnv() === 'prod' && !allowInProduction) || !VERBOSE) return
29+
if (process.env.NODE_ENV === 'test' || process.env.VITEST) return
30+
31+
const status = res.statusCode || 200
32+
const duration = Math.round((performance.now() - startedAt) * 100) / 100
33+
Logger.log([
34+
[`[${req.method}]`, colors[req.method] || 'white'],
35+
[req.url, 'cyan'],
36+
[status.toString(), status >= 500 ? 'red' : status >= 400 ? 'yellow' : 'green'],
37+
[`- ${duration}ms`, 'dim']
38+
], ' ')
39+
})
3740

3841
next()
3942
}
4043

4144
export class RequestLoggerMiddleware {
4245
constructor(private options: { allowInProduction?: boolean } = {}) { }
4346

44-
handler (req: Request, res: Response, next: NextFunction) {
47+
handler(req: Request, res: Response, next: NextFunction) {
4548
const inst = requestLogger(this.options)
4649

4750
return inst.call(inst, req, res, next)

0 commit comments

Comments
 (0)