Wrapping console.log with additional function and correct line numbers

Im struggling to get console.log's to keep the correct line number and preform additional functionality.

var original = console.log

console.log = function() {

   // Can run additional tasks
   console.warn('additional stuff here');

   // Wrong line number given
   console.log.apply.call(original, console, arguments);



I have gone though the following: A proper wrapper for console.log with correct line number?

However i only seem to be able to either keep the correct line or run an additional function from the answer provided but not both.

Thanks all :)

1 answer

  • answered 2018-07-18 10:46 T.J. Crowder

    The reason the line numbers work when using that answer's approach is that console.log is being called directly by the code you want the line number for. With your code above, it isn't, and can't be, because you want to inject behavior.

    The only solution I can think of is a Babel plugin or similar you run on your code, so that the transformed code being output inserts your additional behavior in situ at the call site (not in the called function). E.g., it converts:



    {console.warn("additional stuff here");console.log("foo");}

    or similar. This will be non-trivial (though far from the most complex Babel plugin out there :-) ).