-->

How to log and trace NodeJS Events and Event handl

2019-05-06 19:49发布

问题:

Is there any way to log All other Registered Event handlers when an event handler gets registered?

Also Is there any way to log All Events emitted, and name of handler functions that gets triggered in when an event gets emitted during runtime?

If the nodejs application triggers chained events (one event triggering another ) and each event has multiple handlers, when exception occurs at leaf of event-handler-chain, stacktrace does not show complete information of the context.

Event log and handler info would be quite useful in such a situation.

One hackey solution is to add (conditional) Logging to https://github.com/joyent/node/blob/master/lib/events.js but I am sure there must be a better way.

回答1:

https://github.com/joyent/node/blob/master/lib/events.js#L142-147

It emits a newListener event with the name and function.

Next up, rather than changing events.js, punch the prototype. Once you've required EventEmitter, you can monkeypatch it at runtime. This is bad practice generally, especially for something as critical as EventEmitter, but its fine for debugging your own program.

(function(){
  var old = EventEmitter.prototype.emit;
  EventEmitter.prototype.emit = ...
)();

Next up, log other handlers:

console.log(emitter.listeners('eventName'));