Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Log requests to nodejs express

I want to log all requests like this:

8:04:20 PM - info: /api/v2 200 8:04:22 PM - info: /api/v2/asdf 200

However, in express, the middleware is called before the request is processed, so I cannot get the real response code. I always get 200. What is the right approach to accomplish this?

like image 200
Jose Enrique Avatar asked Dec 23 '22 15:12

Jose Enrique


2 Answers

You can use morgan to log your requests:

const morgan = require("morgan");
app.use(morgan('dev'));

For more documentation visit morgan. Yo may also be interested in on-finished package to execute arbitrary code on request completion.

like image 153
Jose Enrique Avatar answered Dec 28 '22 11:12

Jose Enrique


Here you go:

app.use((req, res, next)=> {
  console.log('I run on every request!');
  next();
})
like image 44
lance.dolan Avatar answered Dec 28 '22 11:12

lance.dolan