如何记录和跟踪NodeJS事件和事件处理程序的调用? [英] How to log and trace NodeJS Events and Event handlers invocation?

查看:159
本文介绍了如何记录和跟踪NodeJS事件和事件处理程序的调用?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

有没有办法在事件处理程序注册时记录所有其他注册事件处理程序?

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

还有什么办法可以记录发出的所有事件,以及如果nodejs应用程序触发链接事件(一个事件触发另一个事件),并且每个事件都有多个处理程序,那么当处理程序函数在运行时发生事件时触发事件处理函数?

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?

事件处理程序链的叶子发生异常,stacktrace不显示上下文的完整信息。

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.

一个hackey解决方案是添加(有条件)记录到 https://github.com/joyent/node/blob/master/lib/events.js ,但我相信必须有更好的方法。

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.

推荐答案

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

它发出带有名称和函数的 newListener 事件。

It emits a newListener event with the name and function.

接下来,而不是更改events.js,打原型。一旦你需要EventEmitter,你可以在运行时监视它。这是一般的糟糕的做法,特别是对于事件重要的事件,如EventEmitter,但它可以调试自己的程序。

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

这篇关于如何记录和跟踪NodeJS事件和事件处理程序的调用?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆