Skip to content

Commit

Permalink
feat: implement a framework-level http requests logger middleware
Browse files Browse the repository at this point in the history
  • Loading branch information
simplymichael committed Jun 21, 2024
1 parent eff7bd9 commit 561ab2d
Show file tree
Hide file tree
Showing 4 changed files with 99 additions and 1 deletion.
1 change: 1 addition & 0 deletions .env.example
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

Expand Down
57 changes: 56 additions & 1 deletion package-lock.json

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

1 change: 1 addition & 0 deletions package.json
Original file line number Diff line number Diff line change
Expand Up @@ -29,6 +29,7 @@
"file-system-cache": "2.4.4",
"http-errors": "2.0.0",
"mongoose": "8.4.1",
"morgan": "1.10.0",
"node-cache": "5.1.2",
"node-laravel-router": "1.0.0",
"object-hash": "3.0.0",
Expand Down
41 changes: 41 additions & 0 deletions src/framework/component/middleware/request-logger.js
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)),
});
}

0 comments on commit 561ab2d

Please sign in to comment.