繁体   English   中英

在没有其他模块的情况下将node.js登录到文件

[英]Logging in node.js to a file, without another module

我正在将节点应用程序作为守护程序运行。 在调试守护程序时,我需要查看输出,因此我想将stdout和stderr重定向到文件。

我希望我可以像在Python或C中那样重新分配stdoutstderr

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

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

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

console对象在首次创建时会获取对process.stdoutstderr的引用。
(您可以在源代码中看到它)。

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

重定向这些流的通常方法是使用重定向的流启动进程。

另外,您可以覆盖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');

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM