-
Notifications
You must be signed in to change notification settings - Fork 0
Commit
This commit does not belong to any branch on this repository, and may belong to a fork outside of the repository.
feat: implement a framework-level http requests logger middleware
- Loading branch information
1 parent
eff7bd9
commit 561ab2d
Showing
4 changed files
with
99 additions
and
1 deletion.
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
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -1,6 +1,7 @@ | ||
NAME="Simple Framework" | ||
HOST=http://localhost | ||
PORT=3000 | ||
URL_SCHEME=http | ||
API_VERSION=1 | ||
NODE_ENV=development | ||
|
||
|
Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.
Oops, something went wrong.
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,41 @@ | ||
const morgan = require("morgan"); | ||
|
||
|
||
module.exports = function logHttpRequests(app) { | ||
let loggerMiddleware; | ||
const logger = app.resolve("logger") || console; | ||
|
||
/* | ||
* If the logger is using log levels different from winston.config.npm.levels, | ||
* we may not have the logger.http method. In that case, | ||
* we fallback to using morgan('tiny') which is an alias for | ||
* morgan(":method :url :status :res[content-length] - :response-time ms"). | ||
*/ | ||
if(typeof logger?.http !== "function") { | ||
loggerMiddleware = morgan("tiny"); | ||
} else { | ||
const config = { | ||
stream: { | ||
/* | ||
* Configure Morgan to use our custom (winston) | ||
* logger with the http severity | ||
*/ | ||
write: (message) => logger.http("incoming-request", JSON.parse(message)), | ||
}, | ||
}; | ||
|
||
loggerMiddleware = morgan(formatter, config); | ||
} | ||
|
||
return loggerMiddleware; | ||
}; | ||
|
||
function formatter(tokens, req, res) { | ||
return JSON.stringify({ | ||
method : tokens.method(req, res), | ||
url : tokens.url(req, res), | ||
status : Number.parseFloat(tokens.status(req, res)), | ||
content_length : tokens.res(req, res, "content-length"), | ||
response_time : Number.parseFloat(tokens["response-time"](req, res)), | ||
}); | ||
} |