Я сделал следующий класс, чтобы "захватить" функцию console.log
. Причина этого заключается в том, что я хочу добавлять и удалять значения
динамически. Он будет использоваться для целей отладки, поэтому важно происхождение вызова функции console.log()
. В следующем коде я объясню свою логику в комментариях.
export class ConsoleLog {
private _isActive = false;
private _nativeLogFn: any;
constructor() {
// ----------------------
// Store the native console.log function, so it can be restored later
// ----------------------
this._nativeLogFn = console.log;
}
public start() {
if (!this._isActive) {
// ----------------------
// Create a new function as replacement for the native console.log
// function. *** This will be the subject of my question ***
// ----------------------
console.log = console.log.bind(console, Math.random());
this._isActive = true;
}
}
public stop() {
if (this._isActive) {
// Restore to native function
console.log = this._nativeLogFn;
this._isActive = false;
}
}
}
Проблема с этой установкой заключается в том, что новая функция назначается в статической форме.
// Function random() generates a number at the moment I assign the function.
// Let say it the number *99* for example sake.
console.log.bind(console, Math.random());
Каждый раз, когда вызывается console.log(...)
, он выдает 99. Таким образом, он довольно статичен. (Чтобы быть впереди вас: нет моей цели не выводить случайное число, LOL, но я просто использую его для проверки, является ли выход динамическим или нет.).
Досадная часть, используя функцию с
console.log.bind
- единственный способ, который я нашел, фактически сохраняя
номер вызывающего абонента и номер строки.
Я написал следующий простой тест.
console.log('Before call, active?', 'no'); // native log
obj.start(); // Calls start and replaces the console.log function
console.log('foo'); // This will output 'our' 99 to the console.
console.log('bar'); // This will output 'our' 99 again.
obj.stop(); // Here we restore the native console.log function
console.log('stop called, not active'); // native log again
// Now if I call it again, the random number has changed. What is
// logical, because I re-assign the function.
obj.start(); // Calls start and replaces the console.log function
console.log('foo'); // This will output N to the console.
// But then I have to call start/log/stop all the time.
Вопрос. Как добавить значения в console.log во время выполнения, не теряя имя и имя вызывающего абонента и номер строки... И без беспокойства потребителя библиотеки, как только этот класс будет запущен с запуском().
EDIT: Добавлен plkr: https://embed.plnkr.co/Zgrz1dRhSnu6OCEUmYN0