node.js 记录 Node 的 stdout 和 stderr
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/23861917/
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
Logging stdout and stderr of Node
提问by raju
I am using the boilerplate code of mean.ioand starting my server with the command:
我正在使用mean.io的样板代码并使用以下命令启动我的服务器:
node server.js
How do I log stdoutand stderrof my Express application?
我如何登录stdout和stderr我的Express应用程序的?
Here's my file server.js:
这是我的文件server.js:
'use strict';
/**
* Module dependencies.
*/
var mongoose = require('mongoose'),
passport = require('passport'),
logger = require('mean-logger');
/**
* Main application entry file.
* Please note that the order of loading is important.
*/
// Initializing system variables
var config = require('./server/config/config');
var db = mongoose.connect(config.db);
// Bootstrap Models, Dependencies, Routes and the app as an express app
var app = require('./server/config/system/bootstrap')(passport, db);
// Start the app by listening on <port>, optional hostname
app.listen(config.port, config.hostname);
console.log('Mean app started on port ' + config.port + ' (' + process.env.NODE_ENV + ')');
// Initializing logger
logger.init(app, passport, mongoose);
// Expose app
exports = module.exports = app;
回答by Steel Brain
What about this?
那这个呢?
console.log("I will goto the STDOUT");
console.error("I will goto the STDERR");
Note:both of these functions automatically add new line to your input.
注意:这两个函数都会自动为您的输入添加新行。
If you don't want those newlines appended to your input, do this
如果您不希望将这些换行符附加到您的输入中,请执行此操作
process.stdout.write("I will goto the STDOUT")
process.stderr.write("I will goto the STDERR")
Both process.stdoutand process.stderrare streams, so you can even pipe a stream into them. See Node.js docs on streamsfor more info.
这两个process.stdout和process.stderr是流,所以你甚至可以通过管道流进他们。有关更多信息,请参阅有关流的 Node.js 文档。
回答by ashu
回答by Ryan
The only way I can think of to do this is to spawn a child process(like the fork system call), which then you can "pipe" the output of stderr, stdoutto files.
我能想到的做到这一点的唯一方法是产生一个child process(如系统调用fork),然后就可以“管”的输出stderr,stdout到文件中。
var out = fs.openSync('./output.log', 'a')
, err = fs.openSync('./error.log', 'a');
require('child_process').spawn('./server', [], {
detached : true,
stdio : ['ignore', out, err]
});

