2

Currently I'm using the NestJs default logging and come up with something like this

@Controller('users')
export class UsersController {
  private logger: Logger = new Logger(UsersController.name, true);

  @Get()
  public getAllUsers(): any[] {
    this.logger.debug('Getting all users', this.getAllUsers.name);
    return [];
  }
}

The log message will show up

[Nest] 2926 - 01/05/2020, 7:39:19 PM [getAllUsers] Getting all users +2094ms

It would be cool to set the context parameter automatically to only need to write

this.logger.debugFunction('Getting all users');

because when logging controller, service and repository functions things could get a bit messy. So from the docs

https://docs.nestjs.com/techniques/logger#extend-built-in-logger

it's possible to extend the default logging behaviour. Taking the example from the docs I would come up with

export class MyLogger extends Logger {
  debugFunction(message: string) {
    super.debug(message, 'this.caller.name');
  }
}

This has been asked before here

How do you find out the caller function in JavaScript?

but this.debugFunction.caller doesn't seem to be a good way because the docs clearly say

enter image description here

Is there a way I can determine the context (caller) automatically in a standard way for production code?

Question3r
  • 2,166
  • 19
  • 100
  • 200
  • 1
    My question would be, do you really need to know the name of the function making the debug statement? If so just throw/catch an exception in the `debugFunction` and capture the stacktrace. From personal experience, using clearer debug messages negates the need for passing in (or determining) the calling function. You could also solve this using a "LoggerFactory" approach which I can show if you're interested... – nerdy beast Jan 06 '20 at 17:49
  • Thanks. It would be cool to have a look at your factory code :) But this question is not critical. I was just asking for a more comfortable way :) – Question3r Jan 06 '20 at 18:32
  • 1
    @Question3r I've got an old implementation of creating a transient logger that took in a context name as a parameter. You can see the code here: https://github.com/jmcdo29/zeldaPlay/tree/64dd32e17e2581d554d640d03675283a1f90b762/apps/api/src/app/logger. I've since created a new logging package that handles it for me which you can find being used in the most recent version of the repository. Might be of some use :) – Jay McDoniel Jan 06 '20 at 22:13
  • 2
    The Worst Possible Way That I Can Think Of to Get The Function Name is below.. `const stack = new Error().stack; const functionName = stack.split('at ')[2].split(' ')[0];` Please forgive me :( – Agnibha Jan 07 '20 at 08:28
  • It amazes me people are trying to write 200 lines of code, just because someone "thinks" `arguments.callee.caller` or `function.caller.name` is not good-looking, or nobody will need it... – Lucas Tettamanti Oct 26 '22 at 14:30

0 Answers0