如何启用没有环境variables的NODE_DEBUG?

我试图在AWS Lambda环境(Node.js 4.3)中运行时,在node.js https库环境中debugging看起来是套接字错误的东西。 这个问题只发生在高度间歇性的情况下,而且只有在高负荷下。 我的团队已经能够在负载testing中重现问题,我们希望启用来自https模块的debugging日志logging。

我在节点文档中发现,通过设置NODE_DEBUG=https环境variables,可以启用debugging日志logging。 但是,我不相信可以设置环境variables: 如何在AWS Lambda上使用环境variables? 。 另外,我没有能力更改Lambda用来调用我的函数的命令行。

是否有另外一种方法来创build与设置NODE_DEBUG相同的debugging日志logging?

这是一个monkeypatch:

 const util = require('util'); let debuglog = util.debuglog; util.debuglog = set => { if (set === 'https') { let pid = process.pid; return function() { let msg = util.format.apply(util, arguments); console.error('%s %d: %s', set, pid, msg); } } return debuglog(set); } // This has to occur _after_ the code above: const https = require('https'); 

它基本上启用httpsdebugging日志logging,无论$NODE_DEBUG 。 易于重写,适用于任何模块,通过Node v4和v6testing。

child_process.fork()允许一个模块产生具有指定环境variables的新节点环境。 这两个进程可以通过send()相互发送消息,并通过“消息”事件接收这些消息。

例如,如果你当前的主模块被命名为server.js ,那么你可以在同样的目录中添加一个临时的start.js模块(这将是新的lambda函数),如下所示:

 // Add NODE_DEBUG to this process's environment variables, which are passed by default to // the forked node environment. process.env.NODE_DEBUG = 'https'; const cp = require('child_process'); const n = cp.fork('server.js'); // Cached callback functions, in case client can pass in different callbacks. // Use an object instead of array, to avoid memory leaks. const cbs = {}; var cbIndexCounter = 0; // To make callback indices unique // Call appropriate callback with response from child process, and delete cached callback. n.on('message', (m) => { cbs[m.cbIndex](m.error, m.result); delete cbs[m.cbIndex]; }); n.on('error', (err) => { console.log('Child node env error: ', err); }); // Cache the callback; forward event, context, index to child process; and increment index. exports.myHandler = function(event, context, callback) { cbs[cbIndexCounter] = callback; n.send({ event: event, context: context, cbIndex: cbIndexCounter++ }); } 

server.js模块可以通过添加一个'message'事件监听器稍作修改:

 process.on('message', (m) => { exports.myHandler(m.event, m.context, function(error, result) { process.send({ error: error, result: result, cbIndex: m.cbIndex }); }); }); // The rest of your original code ... exports.myHandler = function (event, context, callback) { // Whatever you need here... } 

运行以下内容:

 node app.js --https-debug 

并在你的app.js里有这个在脚本的开头

  process.argv.forEach((val, index) => { if(val.match(/--https-debug/)) { process.env.NODE_DEBUG = "https"; } }); 

process.env就像任何对象一样是一个对象,但是node设置了它的环境variables,你总是可以破解它并覆盖从节点全局环境中设置的任何variables。

我们使用process.argv来捕获发送到terminal中的节点js文件的所有参数。

我不熟悉Aws Lambda,但也许你仍然可以像下面的命令导出variables:

 NODE_DEBUG=https node app.js