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

时间:2013-04-22 20:16:15

标签: node.js

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

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

我的代码:

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);
});

5 个答案:

答案 0 :(得分:36)

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

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);
});

答案 1 :(得分:1)

有两种方法可以实现,一种是使用

let logConsoleStream = fs.createWriteStream('./logConsoleFile.log', {flags: 'a'});
let logErrorStream = fs.createWriteStream('./logErrorFile.log', {flags: 'a'});

并使用此重定向所有日志或错误

ls.stdout.pipe(logConsoleStream );  // redirect stdout/logs only
ls.stderr.pipe(logErrorStream );    // redirect error logs only

通过分隔日志文件,您将具有错误日志和控制台日志的单独文件 这与上面共享的generalhenry完全一样

以及在命令行帮助下实现此目标的第二种方式

从命令行执行节点应用程序时

node app/src/index.js

您可以在此处指定要从此应用程序重定向日志和错误的位置

使用命令行有三个流重定向命令

`>`     It will redirect your only stdout or logs to the specified path
`2>`    It will redirect your errors logs to the specified path
`2>&1 ` It will redirect all your stdout and stderr to a single file

示例:如何使用这些命令

node app/src/index.js > ./logsOnly.txt
node app/src/index.js 2> ./ErrorsOnly.txt
node app/src/index.js 2>&1 ./consoleLogsAndErrors.txt

希望以后再来的人会有所帮助

如果我做错了方法,请告诉我它会帮助我和其他人 谢谢

答案 2 :(得分:0)

如果使用forever运行JS脚本,则可以选择将日志文件定义为参数,该文件将处理所有console.log消息。更不用说保持nodejs应用程序永久存在的好处。

或者试试这个:

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

答案 3 :(得分:-1)

永远使用以下选项

永远启动-o out.log -e err.log server.js

答案 4 :(得分:-6)

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

如下:

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