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

I am trying to make a registration service for my TypeScript / Angular 2 application. Unfortunately, if I call console.log, the line number is wrong. Even if I try 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

+4
source share
2 answers

You can use the method .bind()to bind window.consoleto your custom logging method, and then return the function so that the code runs in the original scope when it is called.

log:

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

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

, :

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

TypeScript.


, log, getter, console.log, window.console.

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

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

, , console.log , , .

, :

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

    // Implemnt server-side logging

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

TypeScript.

+2

.trace() .log().

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

.

https://developer.mozilla.org/en-US/docs/Web/API/Console/trace

0

Source: https://habr.com/ru/post/1668426/


All Articles