Anthony
Anthony

Reputation: 4049

How log an HTTP JSON request in Loopback app deployed on Heroku?

An app (Loopback) is deployed on Heroku, and I need to to see the req body (the JSON) send to this app for debugging purpose.

So the access to the log is :

heroku logs --tail

The server.js is like the following :

var loopback = require('loopback');
var boot = require('loopback-boot');

var app = module.exports = loopback();

app.start = function() {
  // start the web server
  return app.listen(function() {
    app.emit('started');
    console.log('Web server listening at: %s', app.get('url'));
  });
};

// Bootstrap the application, configure models, datasources and middleware.
// Sub-apps like REST API are mounted via boot scripts.
boot(app, __dirname, function(err) {
  if (err) throw err;

  // start the server if `$ node server.js`
  if (require.main === module)
    app.start();
});

Upvotes: 2

Views: 3312

Answers (2)

siyb
siyb

Reputation: 2947

If you don't want to modify your server.js file (and why would you), you can register a middleware logging all requests, refer to:

https://docs.strongloop.com/display/public/LB/Defining+middleware#Definingmiddleware-Overview

for more detail on how to register and write a middleware. routes:before would be a good phase to log requests.

Upvotes: 0

Anthony
Anthony

Reputation: 4049

As loopback extends express, we can use body parser module. So first install "body-parser"

Then add this code in serveur.js

var loopback = require('loopback');
var boot = require('loopback-boot');

var app = module.exports = loopback();

var bodyParser = require('body-parser');

// parse application/x-www-form-urlencoded
app.use(bodyParser.urlencoded({ extended: false }))

// parse application/json
app.use(bodyParser.json())

var logger = function(req, res, next) {
  console.log(JSON.stringify(req.body, null, 2));
  next(); // Passing the request to the next handler in the stack.
}
app.use(logger);

...

The remote log will display every request body received by the server.

Upvotes: 3

Related Questions