筛选node.js中的传出请求以进行日志logging
我正在构build一个Express应用程序,它在某些请求中必须进行自己的HTTP调用。 我可以使用Superagent,请求或节点自己的http.request
。 事情是,我需要logging所有这些服务器始发请求和他们各自的答复。 在每一个这样的log.info
之前调用log.info
似乎很愚蠢。
如何为所有传出的HTTP调用添加一个预filter,并理想地访问req
和res
?
注:我不感兴趣的日志请求进入我正在build设的服务器,只有在服务器本身的请求开始。 把我的服务器想象成另一个黑匣子服务器的客户端。
你可以做的是修补http和https并代理request
方法。 这样你就可以有一个全局的处理器来捕获req&res对象。
var http = require('http'); var https = require('https'); var patch = function(object) { var original = object.request; // We proxy the request method object.request = function(options, callback) { // And we also proxy the callback to get res var newCallback = function() { var res = arguments[0]; // You can log res here console.log("RES",res.statusCode); callback.apply(this,arguments); } var req = original(options, newCallback); // You can log your req object here. console.log(req.method,req.path); return req; } } patch(http); patch(https); http.get("http://www.google.com/index.html", function(res) { console.log("Got response"); }).on('error', function(e) { console.log("Got error: " + e.message); });
编辑:这也可以工作,如果你也使用request
npm包,因为它可能只是依靠内置的node.js http.request
方法。
你要用什么服务器为你的应用程序? 我肯定会把这样的function带到服务器级别。 看看heroku路由器是如何做到的。 你可以使用他们的一些插件追踪所有需要的信息:papertrail或newrelic(或分别为你的应用程序使用它们)。
在这种情况下,我喜欢开箱即用的解决scheme,不需要扩展您的应用逻辑来logging这些信息。
如果你想有自己的解决scheme,你可以设置nginx来监视请求/响应信息。 http://nginx.com/resources/admin-guide/logging-and-monitoring/