log4js-node icon indicating copy to clipboard operation
log4js-node copied to clipboard

any MDC so we do not have to pass a logger around?

Open deanbiltup opened this issue 1 year ago • 1 comments

Is there any request context? In java, it was ThreadLocal until async programming...then Twitter invented Context.scala and Promise.scala so MDC in logback could be swapped.

Best with example.

Filter has MDC.put("requestId", generateUniqueReqId());

in the plain old typescript code without passing loggers around all the place(bad smell if we have to pass our logger all around) ->

class SomeBizClass {
    private _logger = createLogger();
    public someMethod(request: FetchPhotosRequest): FetchPhotosResponse {
            _logger.info("My log here"");
           return ...
    }
}

In this case, the output is msg="My log here" requestId="xxxsomeReqIdxxx"

Is this possible? This was an amazing thing about logback and log4j so in GCP, AWS, you simply filtered on requestId and developers never had to remember to

  1. pass a logger around
  2. type in requestId in every single log statement(nor pass requestId around).

It made things 1. extremely efficient and 2. error-prone. (no one every made any errors forgetting to pass a logger or requestID to log it).

deanbiltup avatar Aug 08 '24 11:08 deanbiltup

You don’t need to pass loggers around, when you call log4js.getLogger(“some category”) you’ll get a logger with the same context as any other call with the same category. Logger has a method called addContext which lets you store key value pairs, and the pattern layout lets you output those values in your logs. Should do what you want, give it a try.

nomiddlename avatar Aug 08 '24 12:08 nomiddlename