import { NextFunction , Request , Response } from "express" ; import Logger from "bunyan" ; import { booleanFlag , BooleanFlags } from "../config/feature-flags" ; import { FILTERING_FRONTEND_HTTP_LOGS_MIDDLEWARE_NAME } from "../config/logger" ; declare global { namespace Express { interface Request { addLogFields : ( fields ) => void ; log : Logger ; } } } export default ( req , res , next ) : void => { req . addLogFields = ( fields ) : void => { if ( req . log ) { req . log = req . log . child ( fields ) ; } else { throw new Error ( `No log found during request: ${ req . method } ${ req . path }` ) ; } } ; req . log = req . log . child ( { name : FILTERING_FRONTEND_HTTP_LOGS_MIDDLEWARE_NAME } ) ; res . once ( "finish" , async ( ) => { if ( ( res . statusCode < 200 || res . statusCode >= 500 ) && ! ( res . statusCode === 503 && await booleanFlag ( BooleanFlags . MAINTENANCE_MODE , false ) ) ) { req . log . warn ( { res , req } , `Returning HTTP response of '${ res . statusCode }' for path '${ req . path }'` ) ; } } ) ; next ( ) ; } ;