简体   繁体   English

expressjs 日志记录的最佳实践是什么?

[英]What's the best practice for expressjs logging?

I am building an application based on expressjs and I'd like to log all events in it.我正在构建一个基于 expressjs 的应用程序,我想在其中记录所有事件。 I could find winston, which seems to be cool.我可以找到 winston,这似乎很酷。 Anyway, I am looking for a way how to connect it to my expressjs app.无论如何,我正在寻找一种方法如何将它连接到我的 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路线/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); });
};

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 (eg 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.你知道,我有很多并发请求,我想看看每个请求调用了哪个调试消息。

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. 创建一个公共库,用于围绕我们的定义和传输包装记录器对象,然后处理我们希望以不同方式处理的任何其他类型的对象。

https://gist.github.com/rtgibbons/7354879 https://gist.github.com/rtgibbons/7354879

If you're using express you may want to look at express-winston package. 如果您正在使用快递,您可能需要查看express-winston套餐。 Then you can use winston as middleware and easily log requests/errors without making your code messy... 然后你可以使用winston作为中间件,轻松记录请求/错误,而不会使你的代码混乱......

I love Hirung103 answer, so here is the javascript version:我喜欢Hirung103的回答,所以这是 javascript 版本:

First, add express-request-id and morgan if those libs not listed in your package.json .首先,如果您的package.json中未列出这些库,请添加express-request-idmorgan

Then add these lines inside your server.js :然后在server.js中添加这些行:

...
const addRequestId = require('express-request-id')({
  setHeader: false
})

app.use(addRequestId)

const 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
    }
  )
)
...

thanks to Hirung103感谢Hirung103

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)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM