-
Notifications
You must be signed in to change notification settings - Fork 9
Commit
This commit does not belong to any branch on this repository, and may belong to a fork outside of the repository.
- Loading branch information
1 parent
2a1de22
commit 8192cc8
Showing
3 changed files
with
57 additions
and
2 deletions.
There are no files selected for viewing
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,47 @@ | ||
import { Injectable, Logger, NestMiddleware } from '@nestjs/common'; | ||
import { NextFunction, Request, Response } from 'express'; | ||
|
||
@Injectable() | ||
export class HttpLoggerMiddleware implements NestMiddleware { | ||
private readonly logger = new Logger(HttpLoggerMiddleware.name, { timestamp: true }); | ||
|
||
use(req: Request, res: Response, next: NextFunction) { | ||
const requestStarted = Date.now(); | ||
const { method } = req; | ||
const url = req.originalUrl; | ||
|
||
let finished = false; | ||
|
||
res.on('finish', () => { | ||
const message = `${res.statusCode} ${res.statusMessage} | [${method}] ${url} - ${ | ||
Date.now() - requestStarted | ||
}ms`; | ||
|
||
finished = true; | ||
|
||
if (this.is4xxErrorCode(res.statusCode)) { | ||
this.logger.warn(message); | ||
} else if (this.is5xxErrorCode(res.statusCode)) { | ||
this.logger.error(message); | ||
} else { | ||
this.logger.log(message); | ||
} | ||
}); | ||
|
||
res.on('close', () => { | ||
if (!finished) { | ||
this.logger.warn(`connection closed | [${method}] ${url} - ${Date.now() - requestStarted}ms`); | ||
} | ||
}); | ||
|
||
next(); | ||
} | ||
|
||
is4xxErrorCode(statusCode: number): boolean { | ||
return statusCode >= 400 && statusCode < 500; | ||
} | ||
|
||
is5xxErrorCode(statusCode: number): boolean { | ||
return statusCode >= 500 && statusCode < 600; | ||
} | ||
} |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1 @@ | ||
export * from './http-logger.middleware'; |