使用 node.js 将输出重定向到日志文件

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/16155932/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-02 14:17:10  来源:igfitidea点击:

Redirecting output to a log file using node.js

node.js

提问by user220755

I have a child process that I am using as follows in node.js. Instead of redirecting the output to the console I would like to put the output in a log file located somewhere on the machine this is running on (and should work for both windows and mac).

我有一个子进程,我在 node.js 中使用如下。而不是将输出重定向到控制台,我想将输出放在位于正在运行的机器上某处的日志文件中(并且应该适用于 windows 和 mac)。

The code below is what I am using and I would like to output the files into a log file. What changes needed to do that here? Thanks!

下面的代码是我正在使用的代码,我想将文件输出到日志文件中。在这里需要做哪些改变?谢谢!

My Code:

我的代码:

var spawn = require('child_process').spawn,
    ls    = spawn('ls', ['-lh', '/usr']);

ls.stdout.on('data', function (data) {
  console.log('stdout: ' + data);
});

ls.stderr.on('data', function (data) {
  console.log('stderr: ' + data);
});

ls.on('close', function (code) {
  console.log('child process exited with code ' + code);
});

采纳答案by user220755

The best answer was in the comments and is mentioned in a previous question here: stackoverflow.com/questions/2496710/nodejs-write-to-file

最好的答案是在评论中,并在上一个问题中提到:stackoverflow.com/questions/2496710/nodejs-write-to-file

It is as follows:

如下:

var fs = require('fs');
fs.writeFile("/tmp/test", "Hey there!", function(err) {
    if(err) {
        console.log(err);
    } else {
        console.log("The file was saved!");
    }
}); 

回答by generalhenry

Here's an example of logging to file using streams.

这是使用流记录到文件的示例。

var logStream = fs.createWriteStream('./logFile.log', {flags: 'a'});

var spawn = require('child_process').spawn,
    ls    = spawn('ls', ['-lh', '/usr']);

ls.stdout.pipe(logStream);
ls.stderr.pipe(logStream);

ls.on('close', function (code) {
  console.log('child process exited with code ' + code);
});

回答by swogger

If you run your JS script with foreverthen you have the option to define a log file as parameter which will handle all your console.log messages. Not to mention the benefit of keeping your nodejs app live permanently.

如果你运行你的 JS 脚本,forever那么你可以选择定义一个日志文件作为参数来处理你的所有 console.log 消息。更不用说让您的 nodejs 应用程序永久运行的好处了。

Alternatively try this:

或者试试这个:

sudo forever start myapp.js 2>&1 /home/someuser/myapp/myapp.log

回答by fatih tekin

use forever with below options

使用以下选项永远使用

forever start -o out.log -e err.log server.js

永远开始 -o out.log -e err.log server.js