3

I am using morgan('dev') for logging, but I want to store this object "GET /users/get 200 195.315 ms - 393" [in console log] into database.

like

- method : get 
- endpoint : /users/get
- status : 200

How can I get this object?
How to explode and insert data into field(method, endpoint, status) above on database?

Patrick Hund
  • 19,163
  • 11
  • 66
  • 95

2 Answers2

4

You can create a small middleware that will listen on 'finish' event of Response and save the data into the database:

app.use((req, res, next) => {
  const method = req.method;
  const endpoint = req.originalUrl;

  res.on('finish', () => {
   const status = res.status;
   saveRequestDataToDatabase(method, endpoint, status);
   next();
  });
});
Volodymyr
  • 1,360
  • 1
  • 7
  • 12
  • ok, what if i want to store request body and response to field? how to getting that? – Agung hallman maliki Oct 22 '18 at 04:42
  • If you are using `bodyparser` then you can access Request's body like `req.body`. Getting the body of Response is not that easy because Response is a [Stream](https://nodejs.org/api/stream.html). Usually retrieving Response's body is done by monkey patching of `response.write` and `response.end` methods. You can see how it can be implemented [here](https://stackoverflow.com/questions/19215042/express-logging-response-body) or [here](https://github.com/sirrodgepodge/morgan-body). – Volodymyr Oct 22 '18 at 11:20
1

There are modules already out there that provide stream-compatible interfaces to known storages, such as Mongoose-Morgan which allows you to stream your Mongoose logs directly into MongoDB. However, if you can’t find a morgan-compatible module, you can simply write a function that returns a writable stream and sends the information where you need it. Morgan NPM Logger – The Beginner’s Guide

Create a new named format:

const morgan = require('morgan')
const Writable = require("stream").Writable
morgan.token("custom", "-method: :method -endpoint: :url -status: status")

Use the new format by name:

 class MyStream extends Writable {
    write(line) {
    //here you send the log line to wherever you need
       console.log("Logger:: ", line)
    }
  }
  let writer = new MyStream()
 
 app.use(morgan(‘custom’, {stream: write}))
Mohsen
  • 1,295
  • 1
  • 15
  • 45