@@ -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
4144export 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