简体   繁体   English

使用附加功能和正确的行号包装console.log

[英]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. 我在努力获取console.log来保持正确的行号并执行其他功能。

 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? 我经过以下步骤: 使用正确的行号为console.log正确包装吗?

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 :) 谢谢大家:)

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. 当使用该答案的方法时,行号起作用的原因是console.log被想要行号的代码直接调用。 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). 我能想到的唯一解决方案是在代码上运行的Babel插件或类似程序,以便输出的转换代码可以在调用站点(而不是在被调用函数中) 就地插入其他行为。 Eg, 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 :-) ). 这将是不平凡的(尽管与最复杂的Babel插件相去甚远:-))。

Just for anyone who comes across this i wrote a babel plugin to solve this issue: 我只为遇到此问题的任何人编写了babel插件来解决此问题:

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM