Dunebook / codesource

0 stars 0 forks source link

creating-a-logging-middleware-in-expressjs/ #40

Open utterances-bot opened 1 year ago

utterances-bot commented 1 year ago

Creating a logging middleware in Expressjs

One of the most basic kind of logging every backend application should have is a trace logging of all incoming HTTP requests.

https://codesource.io/creating-a-logging-middleware-in-expressjs/

mactyr commented 1 year ago

This will not log the correct status code or response time because the logging occurs as soon as the middleware is run, which is likely before the final status code and response time are known. In order to log after the request is compeleted, you need to wrap most of the logging code in res.on('finish' () => {...} ). See https://stackoverflow.com/questions/22822684/how-to-hook-after-res-send-but-before-the-response-leaves-the-server-when for a full explanation.