将node.jslogging到文件中,而不使用其他模块

我正在运行一个节点应用程序作为守护进程。 在debugging守护进程时,我需要看到输出,所以我想将stdout和stderrredirect到一个文件。

我希望我可以重新分配stdoutstderr像Python或C:

 fs = require('fs'); process.stdout = fs.openSync('/var/log/foo', 'w'); process.stderr = process.stdout; console.log('hello'); 

当我直接运行脚本时,“hello”被打印到控制台上! 当然,当我在后台运行时,在控制台(当然)或/var/log/foo都看不到输出。

我不想要或需要复杂的日志logging。 我只需要看看节点已经提供的内置消息。

console对象在第一次创build时抓取对process.stdoutstderr的引用。
(你可以在源文件中看到这个)。

稍后重新分配它们不会影响console

redirect这些stream的通常方法是启动redirectstream的过程。

或者,您可以覆盖console方法,并使其写入您的文件。

类似于这个问题 ,你可以覆盖从console.log 调用的 process.stdout.write

 var fs = require('fs'); var oldWrite = process.stdout.write; process.stdout.write = function (d) { fs.appendFileSync('./foo', d); oldWrite.apply(this, arguments); }; console.log('hello');