1

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);

}

console.log('test')

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 :)

OliverRadini
  • 6,238
  • 1
  • 21
  • 46
Peter I
  • 843
  • 1
  • 9
  • 31

2 Answers2

1

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.log("foo");

into

{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 :-) ).

T.J. Crowder
  • 1,031,962
  • 187
  • 1,923
  • 1,875
  • Thanks for this. The project gets ran though babel, have you got an example of how to get this to work though babel please? – Peter I Jul 18 '18 at 11:38
  • @PeterI - No, that would be rather too broad for an SO answer. There are dozens of open source Babel plugins, though, shouldn't be too hard to find examples of what you need to do. – T.J. Crowder Jul 18 '18 at 11:43
1

Just for anyone who comes across this i wrote a babel plugin to solve this issue:

https://github.com/peteringram0/babel-plugin-console-source

Peter I
  • 843
  • 1
  • 9
  • 31