4

In a nutshell: can one associate logs (throughout an entire node API) to a certain (dynamic) reference ID?

[Explained further]
So, here is the situation: I am writing an API that potentially handles up to hundreds of requests at one time. It is implemented in Node.js and Express. I have extensive logging throughout the API and each log has to have a unique reference ID so that I can related several logs to the same request.

One way I can do this is by randomly generating a string and passing it as a parameter to every function call (I am keeping this as a last resort). I do not want to do this

To reiterate,

  • request comes in
  • randomly generate string: aljsndci.json
  • append (Express) request.body to aljsndci.json
  • do internal logic in API
    • log in json format, each log must contain key { ... file: 'aljsndci.json' ... }
  • append (Express) response to aljsndci.json
  • response through express

I have stumbled upon solutions like continuation-local-storage, however, how does one generate a unique string (for namespace) and then reference that same string later? All the examples here hard code the string for the namespace. Is there are example, similar to the one here (found here)

var getNamespace = require('continuation-local-storage').getNamespace;
var session = getNamespace('my session');

var render = require('./lib/render.js')

function finish(response) {
  var user = session.get('user');
  render({user: user}).pipe(response);
}

where instead of var session = getNamespace('my session');, it actually calls the names of the series of callbacks from this point on? Something like var thisNamespace = getNamespace(this);

Basically if I could set a global variable for every subsequent callback, that would solve this problem

Jeremy
  • 1,717
  • 5
  • 30
  • 49
  • 2
    With Express.js, req is available in each middlewares. You could use it by putting your generated unique id in req.uniqueId for example. – Mathieu Lordon Apr 25 '16 at 12:42

1 Answers1

2

I think the same exactly problem was solved in this question: How to identify request (by ID) through middleware chain in Express. Check it and if you have any doubts say it here or in the other question.

David Vicente
  • 3,091
  • 1
  • 17
  • 27