记录所有请求

时间:2014-05-14 04:58:26

标签: node.js express

我有日志记录的问题,但我不知道如何阻止它,我只是想让它记录视图文件而不是静态文件..

这是我的代码:

//logger.
app.use(function(request, response, next)
{
    if(app.get('env') == 'development')
    {
        console.log('%s %s', request.method, request.url);
        console.log('connection from: ' + request.ip);
    }

    var file = request.url.slice(1 + request.url.indexOf('/'));

    app.get(request.url, function(request, response)
    {
        response.render(file,
        {
            //Var to be named in the render : value;
            'Title': Title,
            'result': result
        });
    });

    next();
});


//Set directory for static files (css, js, img)
app.use(express.static(__dirname + '/public'));

当我进入控制台查看结果时。我明白这个

GET /css/bootstrap.css
connection from: 127.0.0.1
GET /css/cover.css
connection from: 127.0.0.1
GET /index
connection from: 127.0.0.1
GET /css/cover.css
connection from: 127.0.0.1
GET /css/bootstrap.css
connection from: 127.0.0.1

我只是希望它记录GET /index而不记录其余部分。

1 个答案:

答案 0 :(得分:1)

如果您正在使用express.js,只需使用记录中间件,例如' morgan'并让express为您处理日志记录。例如,以下代码将自动打印一些日志记录:

var express = require('express');
var morgan = require('morgan');  // Logging middleware
var app = express();

app.use(morgan('dev'));  // 'dev', 'short', 'tiny'. or no argument (default)
app.get('/', function(req, res){
    res.send('hello world');
});
app.listen(3000);

当你点击localhost:3000时,你会看到来自快递的记录为(也是彩色):

GET / 200 3ms - 11b