import { CallHandler , ExecutionContext , HttpException , HttpStatus , Injectable , Logger , NestInterceptor , } from '@nestjs/common' ; import { Request , Response } from 'express' ; import { Observable } from 'rxjs' ; import { tap } from 'rxjs/operators' ; /**
 * Interceptor that logs input/output requests
 */ @ Injectable ( ) export class LoggingInterceptor implements NestInterceptor { private readonly ctxPrefix : string = LoggingInterceptor . name ; private readonly logger : Logger = new Logger ( this . ctxPrefix ) ; private userPrefix : string = '' ; /**
     * User prefix setter
     * ex. [MyPrefix - LoggingInterceptor - 200 - GET - /]
     */ public setUserPrefix ( prefix ) { this . userPrefix = `${ prefix } - ` ; } param context param call$ public intercept ( context , call$ ) { const req = context . switchToHttp ( ) . getRequest ( ) ; const { method , url , body , headers } = req ; const ctx = `${ this . userPrefix }${ this . ctxPrefix } - ${ method } - ${ url }` ; const message = `Incoming request - ${ method } - ${ url }` ; this . logger . log ( { message , method , body , headers , } , ctx ) ; return call$ . handle ( ) . pipe ( tap ( { next : ( val ) : void => { this . logNext ( val , context ) ; } , error : ( err ) : void => { this . logError ( err , context ) ; } , } ) ) ; } param body param context private logNext ( body , context ) { const req = context . switchToHttp ( ) . getRequest < Request > ( ) ; const res = context . switchToHttp ( ) . getResponse < Response > ( ) ; const { method , url } = req ; const { statusCode } = res ; const ctx = `${ this . userPrefix }${ this . ctxPrefix } - ${ statusCode } - ${ method } - ${ url }` ; const message = `Outgoing response - ${ statusCode } - ${ method } - ${ url }` ; this . logger . log ( { message , body , } , ctx ) ; } param error param context private logError ( error , context ) { const req = context . switchToHttp ( ) . getRequest < Request > ( ) ; const { method , url , body } = req ; if ( error instanceof HttpException ) { const statusCode = error . getStatus ( ) ; const ctx = `${ this . userPrefix }${ this . ctxPrefix } - ${ statusCode } - ${ method } - ${ url }` ; const message = `Outgoing response - ${ statusCode } - ${ method } - ${ url }` ; if ( statusCode >= HttpStatus . INTERNAL_SERVER_ERROR ) { this . logger . error ( { method , url , body , message , error , } , error . stack , ctx ) ; } else { this . logger . warn ( { method , url , error , body , message , } , ctx ) ; } } else { this . logger . error ( { message : `Outgoing response - ${ method } - ${ url }` , } , error . stack , `${ this . userPrefix }${ this . ctxPrefix } - ${ method } - ${ url }` ) ; } } }