nest-winston: Context is lost when logging errors

While debugging while certain log entries were missing the context property, I found out that it seems that the context is lost when calling the .error() method. Here is some example code:

import { Injectable, Logger } from '@nestjs/common';

@Injectable()
export class MyService {
  private logger = new Logger(this.constructor.name);

  constructor() {
    this.logger.log('this is a test log')
    this.logger.error('this is a test error')
  }
}

Which gives this output with the json formatter:

{"context":"MyService","label":"application-platform-latency-tester","level":"info","message":"this is a test log"}
{"label":"application-platform-latency-tester","level":"error","message":"this is a test error","stack":["MyService"]}

As you can see, the first log entry is fine. The second log entry with the error is putting the context in the stack property.

With the same code, the default Nest logger keeps the context in the right place:

[Nest] 82543  - 06/05/2022, 17:37:30     LOG [MyService] this is a test log
[Nest] 82543  - 06/05/2022, 17:37:30   ERROR [MyService] this is a test error

About this issue

  • Original URL
  • State: closed
  • Created 2 years ago
  • Comments: 15 (9 by maintainers)

Commits related to this issue

Most upvoted comments

@xunziheng is correct. This is a bug. The cause of this is that the NestJS Logger class is delegating the error() message to WinstonLogger, and in the case that a stack trace is not provided, it will invoke error() with only two arguments (message, context).

This is supported by the type definition (stack is an optional parameter) and should work. However, WinstonLogger is erroneously treating this invocation as (message, stack) as opposed to (message, context), so the context winds up in the stack trace instead.

In the case that WinstonLogger.error() is invoked with two arguments, the second argument should be treated as context and not as stack. This matches the expectation that NestJS has of its loggers.

I’m sorry for the very late response, I’m quite busy recently with my personal and working life. I’ll try to follow more this library that, honestly, went so far and has been used by many. Didn’t expected that 😄

@faithfulojebiyi you seems more on the point than me, can i close this?

I can confirm that @ChrisiPK’s pull request fixed this for me! It works fine now in NestJS 9.3.1 🥳