Yar*_*Dot 52 logging node.js express
我正在构建一个基于expressjs的应用程序,我想记录它中的所有事件.我能找到温斯顿,这看起来很酷.无论如何,我正在寻找一种方法如何将它连接到我的expressjs应用程序.
我还想要的是登录应用程序.我的要求并不那么简单,所以我想记录我的应用程序中的所有内容(不仅仅是请求).
我目前的情况:
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);
Run Code Online (Sandbox Code Playgroud)
路线/ something.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); });
};
Run Code Online (Sandbox Code Playgroud)
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;
Run Code Online (Sandbox Code Playgroud)
我正在考虑的另一件事是将所有事件记录在从控制器调用的函数中(例如模型或其他库).
所以我认为,创建一些记录器库的好方法可能是使用:
var logger = require(__dirname + '/../libraries/logger.js');
Run Code Online (Sandbox Code Playgroud)
包含记录器定义.我不知道如何解决的另一个问题是如何为数据添加前缀.你知道,我有很多并发请求,我想看看每个请求调用了哪个调试消息.
Rya*_*ons 28
我们使用winston,它可能是最强大的日志包.
我们最终完全像你建议的那样设置它.创建一个公共库,用于围绕我们的定义和传输包装记录器对象,然后处理我们希望以不同方式处理的任何其他类型的对象.
https://gist.github.com/rtgibbons/7354879
如果您正在使用快递,您可能需要查看express-winston套餐.然后你可以使用winston作为中间件,轻松记录请求/错误,而不会使你的代码混乱......
我喜欢以下 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
Run Code Online (Sandbox Code Playgroud)
下面的代码可以做到这一点
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)
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
47239 次 |
| 最近记录: |