Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
385 views
in Technique[技术] by (71.8m points)

logging - Is there a way to wrap all JavaScript methods with a function?

I want to wrap every function call with some logging code. Something that would produce output like:

func1(param1, param2)
func2(param1)
func3()
func4(param1, param2)

Ideally, I would like an API of the form:

function globalBefore(func);
function globalAfter(func);

I've googled quite a bit for this, but it seems like there's only aspect-oriented solutions that require you to wrap the specific functions you want to log, or whatever. I want something that applies to every function in the global scope (except itself, obviously).

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

A simple approach would be something like this

var functionPool = {} // create a variable to hold the original versions of the functions

for( var func in window ) // scan all items in window scope
{
  if (typeof(window[func]) === 'function') // if item is a function
  {
    functionPool[func] = window[func]; // store the original to our global pool
    (function(){ // create an closure to maintain function name
         var functionName = func;
         window[functionName] = function(){ // overwrite the function with our own version
         var args = [].splice.call(arguments,0); // convert arguments to array
         // do the logging before callling the method
         console.log('logging: ' + functionName + '('+args.join(',')+')');
         // call the original method but in the window scope, and return the results
         return functionPool[functionName].apply(window, args );
         // additional logging could take place here if we stored the return value ..
        }
      })();
  }
}

To undo you would need to run the

for (func in functionPool)
  window[func] = functionPool[func];

Notes
This handles only global functions, but you can easily extend it to handle specific objects or methods etc..


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...