I've trying to create a custom logger middleware without any package or library It's as simple as saving the endpoint, the method and the status code response.
I have the problem when I try to save the status code, since my response has not yet reached the controller. I was trying to understand how morgan does it, because it is the first middleware I use and when my backend responds, it logs the status code.
Is there a simple way without me having to modify all my backend controllers?
Or rather, how can I access the res.status of a controller from this middleware?
const createLog = (req, res, next) => {
const { method, url } = req;
const { statusCode, statusMessage } = res;
console.log(statusCode, statusMessage); // Both null when reach the middleware
next();
};
The following middleware logs the request method, URL and status (which is available only when the request has finished):
const createLog = (req, res, next) => {
res.on("finish", function() {
console.log(req.method, decodeURI(req.url), res.statusCode, res.statusMessage);
});
next();
};
Alternatively, you can register the following event handler on your HTTP(S) server, which logs all HTTP requests (>
) and responses (<
), but this may be overwhelmingly much:
server.on("connection", function(socket) {
const write = socket.write.bind(socket);
socket.on("data", function(chunk) {
console.log(">", chunk.toString());
});
socket.write = function(chunk, encoding, callback) {
write(chunk, encoding, function (err) {
console.log("<", chunk.toString(encoding || "utf8"));
if (callback) callback(err);
});
};
});