Javascript – Extending console.log without affecting log line

google-chromejavascript

I would like to extend the 'console.log' function to add additional information to its output – but I dont want to affect the script name/line number information generated by the browser in the console window. See how if I create my own implementation, I get useless trace information, should I want to locate that region of code… (they all link to the log implementation, not the actual script that caused the log message)

enter image description here

Basically, my application is a very pluggable infrastructure, were any log output may occur within any number of frames.
As such, I want every log message to include a special unique identifier at the beginning of the log message.

I have tried replacing the console.log method with my own, but chrome complains with
Uncaught TypeError: Illegal invocation

this is how I override it

var orig = console.log;
console.log = function( message )
{
    orig( (window == top ? '[root]' : '[' + window.name + ']') + ': ' + message );
}

Any ideas?

[EDIT]
Note: After fixing the 'illegal invocation' problem, it seems the filename/linenumber is still 'polluted' by the override…

[EDIT]
It looks like the general answer is – NO – despite some confusing goose chases, the desired functionality is NOT achievable in the current versions of browsers.

Best Answer

Yes, it is possible to add information without messing up the originating line numbers of the log invocation. Some of the other answers here came close, but the trick is to have your custom logging method return the modified logger. Below is a simple example that was only moderately tested that uses the context variant.

log = function() {
    var context = "My Descriptive Logger Prefix:";
    return Function.prototype.bind.call(console.log, console, context);
}();

This can be used with:

log("A log message..."); 

Here is a jsfiddle: http://jsfiddle.net/qprro98v/

One could get easily get creative and pass the context variable in, and remove the auto-executing parens from the function definition. i.e. log("DEBUG:")("A debug message"), log("INFO:")("Here is some info"), etc.

The only really import part about the function (in regards to line numbers) is that it returns the logger.