Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Keeping console.log() line numbers in a wrapper function in TypeScript / Angular 2

I am try to make a logging service for my TypeScript / Angular 2 App. Unfortunately if i call console.log the line number is wrong. Even if i try to return console.log().

Here is my code:

LoggerService.ts

export class LoggerService {    
  log(message) {
    // Server-side logging
    // [...]
    if (clientSideLogging) return console.log(message);
  }
}

SomewhereElse.ts

this.logger.log('hello world');

-> Shows line number of LoggerService.ts instead of source

like image 333
Mick Avatar asked Jan 31 '17 16:01

Mick


1 Answers

You could use the .bind() method to bind window.console to your custom log method and then return the function so that the code is executed within the original scope when it is called.

In doing so, the line number will be preserved when calling the logger service's log method:

class LoggerService {
  public log = console.log.bind(window.console);
}

// ...or annotated:
class LoggerService {
  public log: (message) => void = console.log.bind(window.console);
}

Then if you want to add in your conditional statement:

class LoggerService {
  public log = clientSideLogging ? console.log.bind(window.console) : () => {};
}

Here is an example with the compiled TypeScript code.


Aside from the one-liner solutions mentioned above, if you want to implement additional logic inside of the log method, then you could utilize a getter which will return and call the console.log function that is bound to window.console.

class LoggerService {
  public get log (): Function {
    // Implemnt server-side logging

    return console.log.bind(window.console);
  }
}

As you can tell, it is important for the console.log function to be returned since it will not preserve the line numbers when it is called directly within another scope.

Then if you want to add in your conditional statement:

class LoggerService {
  public get log (): Function {
    const log = console.log.bind(window.console);

    // Implemnt server-side logging

    return clientSideLogging ? log : () => {};
  }
}

Here is an example with the compiled TypeScript code.

like image 147
Josh Crozier Avatar answered Oct 22 '22 09:10

Josh Crozier