nestlogger icon indicating copy to clipboard operation
nestlogger copied to clipboard

setContext does not work correct

Open cesc1802 opened this issue 4 years ago • 5 comments

export class SecurityService {
  constructor(
    private readonly logger: LoggerService
  ) {
    this.logger.setContext(`SecurityService`);
  }
}

export class SecurityService1 {
  constructor(
    private readonly logger: LoggerService
  ) {
    this.logger.setContext(`SecurityService1`);
  }
}

it alway get context is SecurityService

cesc1802 avatar Jun 07 '20 16:06 cesc1802

LoggerService is a singleton when injected to another services so it can have only one context. It would be nice if you could use it like this though.

You could probably inject it in request scope to make it work but there's a performance cost if done like that. Here's the doc how to do it: https://docs.nestjs.com/fundamentals/injection-scopes

jukkahell avatar Jun 08 '20 17:06 jukkahell

So i mean if i want to have multiple context. I must be create many logger instance. And it effect to performent of my application

cesc1802 avatar Jun 09 '20 15:06 cesc1802

It means that a new instance is created on each request. That shouldn't be too bad but on a heavy load it would affect. It would be possible to create multiple instances as well but I'm not sure how that would affect if they're configured to use the same log file. The easiest and most robust thing would be to set the context on every log call.

jukkahell avatar Jun 09 '20 21:06 jukkahell

That being said, it won't work too good currently. However, there might be some ways to fix this. I can take a look at it at some point. Or if you have any ideas, I'm more than happy to accept a pull request for this.

jukkahell avatar Jun 09 '20 21:06 jukkahell

thanks, i think i will setContext every log call.

cesc1802 avatar Jun 10 '20 01:06 cesc1802