puzpuzpuz / cls-rtracer

Request Tracer - CLS-based request id generation for Express, Fastify, Koa and Hapi, batteries included
MIT License
311 stars 24 forks source link

Can you set a unique id? #69

Closed TannerS closed 1 year ago

TannerS commented 1 year ago

We have a trace id coming from a third party service and would like to use that one, in that request for the logs in our service that calls it. is that possible? here is an example of what we are hoping for

const rTracer = require('cls-rtracer');

const fakeEndpoint = async (req, res) => {
  const traceIdFromThirdParty = req.traceId;

  rTracer.setId(traceIdFromThirdParty);
}
puzpuzpuz commented 1 year ago

Hi. requestIdFactory config param serves exactly this purpose:

const rTracer = require('cls-rtracer');

app.register(rTracer.fastifyPlugin, {
  // This function will be used to initialize the request id at the beginning of each request.
  requestIdFactory: (req) => req.traceId
});

const fakeEndpoint = async (req, res) => {
  console.log('here is my 3rd-party request id: ' + rTracer.id());
};
TannerS commented 1 year ago

hey @puzpuzpuz , dumb question, this is assuming app is the server and your adding it like a middleware? this may not work for us, the server lib we use doesnt allow custom middlewares, is there any other option?

TannerS commented 1 year ago

or do we need the fastify?

puzpuzpuz commented 1 year ago

If you don't have a web server or don't use one of the supported frameworks, you should use AsyncLocalStorage directly instead of cls-rtracer.

TannerS commented 1 year ago

@puzpuzpuz hello, thanks for the reply, and ya we do have a web server but its a custom company made one that doesnt allow injection of middlewares (really stupid i know crys), so inthis example, we would need to set the id on an method (now that i look at it, no request at all object just a normal function) then use that trace id rest of the code base that calls the id function, if that is able to so with AsyncLocalStorage, do you have any examples? thanks !

or is there any possible way to make this lib work?

puzpuzpuz commented 1 year ago

if that is able to so with AsyncLocalStorage, do you have any examples?

That's not cls-rtracer API, so you should refer to the standard library documentation: https://nodejs.org/api/async_context.html#class-asynclocalstorage

TannerS commented 1 year ago

ok ill look, thank you, ill close this but i may have question in future :) thanks!