1

We are adding correlation id's to our node express app, to tie requests together. This id is sent in the header from other services and our middleware collects the id, creates a bunyan logger with the id and adds it to the request object.

Our routes currently look like the following:

 router.get('', (req, res, next) => {
    service.doSomething(req.params.userid)
      .then(items => res.json(items))
      .catch((err) => next(err));
  });

The current proposed solution is something like the following:

 router.get('', (req, res, next) => {
    let logger = req.log;
    service.doSomething(req.params.userid, logger)
      .then(items => res.json(items))
      .catch((err) => next(err));
  });

This would mean that the doSomething and each function it calls would need to accept the logging object as a parameter. This means that nearly each function would need to accept a logging object.

For example:

function add(a, b, log) {
  log.debug("Trivial example");
  return a + b;
}

Is there a better way to do this logging on a per request basis, without passing a logging object to each function?

nazerb
  • 319
  • 1
  • 2
  • 11

1 Answers1

0

You can use an express middleware app.use for this.

register the middleware before the endpoints are registered and handle the logging there.

var express = require('express');
var app = express();

// register middleware here
app.use(function(req,res,next){


    service
           .doSomething.call(req)
           .then(items => res.json(items))
           .catch((err) => next(err)); 

    next();
});



app.get('/', function (req, res) {
  res.send('Hello World!');
});

app.listen(3000, function () {
  console.log('Example app listening on port 3000!');
});

By this you can access the do something method with the same scope as the callback function itself. The req.log can then be accessed via this.log. Even the req.params.userIdcan be accessed then via this.params.userId

Hope that helps.

Bernhard
  • 4,855
  • 5
  • 39
  • 70