0

I am trying to log the session user but its not working as i suspected. I was thinking i could add it in the middle ware but clearly this wont work. Is there a strategy or pattern i should be using to accomplish this.

The PassportAuthInterceptor log should have distinct users but its only using the last one set by the Middleware

I see them using it in the log4js documentation but clearly this doesnt seem to make sense the way i demonstrated below.

I also see that the have a AuthLibrary.currentUser() call, but im unsure how to accomplish this.

https://github.com/log4js-node/log4js-node/blob/master/docs/layouts.md#tokens

seeing as how this is NestJS, can i inject the user into a service somehow as that could solve my problem.

export class LoggerMiddleware implements NestMiddleware {

    private readonly logger = new AppLoggerService(LoggerMiddleware.name);

    public use(req, res, next: () => void) {

        log4js.getLogger('default').addContext('user', user.authName)

        next();
    }
}

enter image description here

Ricardo Saracino
  • 1,345
  • 2
  • 16
  • 37

1 Answers1

0

So this is kinda gross but it works, i created 2 loggers one global (normal) and one session (scope request). The thing is that any class that is used by passport login cannot reference the SessionLoggerService .. This will have me split classes as global and Session so the classes they call can use the correct logger.

https://github.com/nestjs/nest/issues/1870

@Injectable({scope: Scope.REQUEST})
export class SessionLoggerService implements LoggerService {

    public static logger = undefined;

    constructor(@Inject(REQUEST) private readonly req) {
        SessionLoggerService.logger = log4js.getLogger('user');

        const user = this.req && this.req.user ? this.req.user : null;

        if (user) {
            SessionLoggerService.logger.addContext('user', user.authName);
        } else {
            SessionLoggerService.logger.addContext('user', '');
        }
    }

    ....
}
Ricardo Saracino
  • 1,345
  • 2
  • 16
  • 37