node.js expressjs 日志记录的最佳实践是什么?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/19835652/
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
What's the best practice for expressjs logging?
提问by Yarik Dot
I am building an application based on expressjs and I'd like to log all events in it. I could find winston, which seems to be cool. Anyway, I am looking for a way how to connect it to my expressjs app.
我正在构建一个基于 expressjs 的应用程序,我想在其中记录所有事件。我可以找到温斯顿,这似乎很酷。无论如何,我正在寻找一种如何将它连接到我的 expressjs 应用程序的方法。
What I also want is logging inside the application. My reqeusts are not so simple, so I'd like to log everything inside my app (not only requests).
我还想要的是在应用程序中登录。我的请求不是那么简单,所以我想在我的应用程序中记录所有内容(不仅仅是请求)。
My current situation:
我现在的情况:
server.js(I'd like to log http requests on this level)
server.js(我想在这个级别记录 http 请求)
var express = require('express');
var app = express();
var fs = require('fs');
// Post parser
app.configure(function(){
app.use(express.bodyParser());
});
// Load routes
require('fs').readdirSync(__dirname + '/routes').forEach(function(file) {
require(__dirname + '/routes/' + file)(app);
});
// 404: Not found
app.use(function(req, res, next){
res.json(404, {ERROR: 'Page not found.'});
});
// 500: Error reporing
app.use(function(err, req, res, next){
console.error(err.stack);
res.json(500, {ERROR: 'Internal server error.'} );
});
// Startup new server
app.listen(900);
routes/something.js
路线/东西.js
var something = require(__dirname + '/../controller/something.js');
module.exports = function(app) {
app.get('/v1/something', function(req, res, next) { new something().getAll(req, res, next); });
};
controller/something.js(I'd like to use the same logger for debug logging)
controller/something.js(我想使用相同的记录器进行调试日志记录)
/**
* Constructor
*
*/
function Something() {
};
/**
* Get all the data
*
*/
Something.prototype.getAll = function(req, res, next) {
// I want to log some very important information here
res.json({result: true, data: ['hello', 'hi', 'ciao', 'buf']});
}
module.exports = Something;
The other thing I am thinking about is logging all the events in functions that are called from controllers (e.g. models or other libraries).
我正在考虑的另一件事是记录从控制器(例如模型或其他库)调用的函数中的所有事件。
So I think, the good way might to create some logger library, that will be called using:
所以我认为,创建一些记录器库的好方法可能会被调用:
var logger = require(__dirname + '/../libraries/logger.js');
containing logger definition. The other issue I don't know how to solve is how to prefix data. You know, I have a lot of concurrent requests and I'd like to see which debug message was called by each request.
包含记录器定义。我不知道如何解决的另一个问题是如何为数据添加前缀。您知道,我有很多并发请求,我想查看每个请求调用了哪条调试消息。
采纳答案by Ryan Gibbons
We use winston, it's probably the most robust logging package out there.
我们使用winston,它可能是最强大的日志包。
We ended up setting it up exactly like you suggested. Creating a common library used for wrapping the logger object around our definitions and transports, and then handling any other type of objects we want to be handled differently.
我们最终完全按照您的建议进行了设置。创建一个公共库,用于将 logger 对象包装在我们的定义和传输周围,然后处理我们希望以不同方式处理的任何其他类型的对象。
回答by ciny
If you're using express you may want to look at express-winstonpackage. Then you can use winston as middleware and easily log requests/errors without making your code messy...
如果您使用 express,您可能需要查看express-winston包。然后您可以使用 winston 作为中间件并轻松记录请求/错误而不会使您的代码变得混乱......
回答by Hirurg103
I love the following Rails-style logging:
我喜欢以下 Rails 风格的日志:
[2017-11-02T11:13:54.545 #07738a81] Started GET /api/url for 10.0.0.1
[2017-11-02T11:13:54.550 #07738a81] Completed 200 31739 in 5.635 ms
The code below does it
下面的代码做到了
addRequestId = require('express-request-id')(setHeader: false)
app.use(addRequestId)
morgan = require('morgan')
morgan.token('id', (req) -> req.id.split('-')[0])
app.use(morgan(
"[:date[iso] #:id] Started :method :url for :remote-addr",
immediate: true))
app.use(morgan("
[:date[iso] #:id] Completed :status :res[content-length] in :response-time ms"))
app.use('/api', router)

