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

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

Logging stdout and stderr of Node

node.jsexpressmean-stack

提问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?

我如何登录stdoutstderr我的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.stdoutprocess.stderr是流,所以你甚至可以通过管道流进他们。有关更多信息,请参阅有关流的 Node.js 文档

回答by ashu

You can do this by writing to stdout and stderr streams

您可以通过写入 stdout 和 stderr 流来做到这一点

process.stdout.write('Hello')

or

或者

process.stderr.write('Error')

Better will be to use some thirdparty logging module like winstonor bunyan

最好使用一些第三方日志记录模块,如winstonbunyan

回答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),然后就可以“管”的输出stderrstdout到文件中。

var out = fs.openSync('./output.log', 'a')
  , err = fs.openSync('./error.log', 'a');

require('child_process').spawn('./server', [], {
    detached    : true,
    stdio       : ['ignore', out, err]
});