Maintaining RequestId or session variable server-side

Hi
I am trying to improve logs on the server, so that we are able to trace logs with a particular request originating from client. For this reason we want to append request-id in front of each log lines.

When a request(method call from client, publication from client, rest api calls via restivus) originates from client, internally it can call different methods. Logs within all these different methods or functions should reflect same request-id in the log lines. Different calls originating externally should have different requst-ids.

The biggest challenge is maintaining request-id. one way could be to generate request-id at the entry point, and pass it to every other function and so on. This would work but very hectic to change the existing code when so many function calls are there. It’s also prone to errors.

Is there a way, to create a common storage(object) whose reference can accessed from different methods if these methods were part of same external call stack. And for a different external call, it points to the different object(having different request-id)

this.connection.id works inside methods and publications, and we can store any other variable as well within it, but there are 2 issues with this. 1. It does not work within restivus api requests. 2. for different methods calls from client, it gives same connection object.

Thanks

You’re looking for a meteor environment variable. This is unrelated to System env vars. Every fiber has its own environment, at the entry point you set it then you have access to it everywhere. It is automatically propagated between fibers for promises and I believe defers, though if it isn’t propagated on defer it would be easy to add

global.requestId = new Meteor.EnvironmentVariable()

global.requestId.withValue(id, () => {
  //Any function called from here can access global.requestId.get()
})

It’s sad this either isn’t well documented or it’s hard to find (searching for it leads to the system env vars meteor recognizes) but it’s insanely useful.