Filtering console.logging

Excerpt

Using console logging functionality in the browser can be extended by adding a filtering function BEFORE sent to the console.

Using debug output during development and error analysis is one of the most important features. Especially when analyzing time critical codings using the debugger will possibly create corrupted results.

As shown some days before in Standard console.logging there are many useful functions available and the console implementation in the browser also has some nice features for showing or hiding messages to get the relevant entries for analysis.

But when analyzing time critical codings a filter before actually sending information to the console is helping focusing to the problem to be analyzed.

Intersect console.debug calls

Gladfully browsers allow re-assigning the functions in the console API so we can intersect the functions:

// intersect the console.debug function:
const originalFunction = console.debug;

console.debug = function () {
  // do something with the arguments
  // ...

  // do the logging...
  originalFunction.apply(this, arguments);
}

Here the original console.debug function is saved in the variable originalFunction and is called with the same arguments using the apply method. This can be repeated with the other functions like info, warn and error.

Implementing a filter and on/off switch

(The console.debug function is used but the mechanism can be used for info, log and other logging functions.)

Now we can look into the arguments and can do something with it. For filtering and printing the given arguments can be converted to a string so we can look for patterns:

// simple arguments formatting
function formatArguments(args) {
  var out = Array.from(args).map((a) => String(a));
  return (out.join(' '));
}

A global variable debugFilter can be used to only log cases with a given prefix. A global variable debugEnabled can be used to turn console.debug logging on and off.

// global filter settings
let debugFilter = "";
let debugEnabled = true;

// filter console.debug function
const originalFunction = console.debug;

console.debug = function () {
  const s = formatArguments(arguments);
  if ((debugEnabled) && (s.includes(debugFilter))) {
    originalFunction.apply(this, arguments);
  }
}

Example

In the script of this page several console.debug calls with prefix

When opening the console all events will be shown.

To filter the events to a specific prefix run the following lines in the console:

debugFilter='time:' // show only time events
debugFilter=''      // show all events
debugEnabled=false  // disable debug events
debugEnabled=true   // enable debug events

See Also

Tags

JavaScript