Node.js:启用流式传输后,Morgon日志未记录完整的响应时间

时间:2018-11-10 07:15:34

标签: node.js express morgan

我有一个代码,该代码使用nodejs进行简单HTML流传输并进行表达。第一个流发生在第3秒,第二个流发生在第6秒,最后一个流发生在第9秒。该代码与Morgon日志一起启用,以记录响应时间。通过Morgon记录的响应时间显示为3秒(记录第一个流的响应时间)。启用流式传输后,在Morgon,nodejs或express中有没有一种方法可以获取完整的响应时间?帮助非常感谢。

var express = require("express");
var bodyParser = require('body-parser');
var utf8 = require('utf8');
var axios = require('axios');
var morgan = require('morgan')
var fs = require('fs')
var path = require('path')
var app = express();
var port = 3000;
app.use(bodyParser.urlencoded({ extended: false }));
var urlencodedParser = bodyParser.urlencoded({ extended: true })
app.use(function(req, res, next) {
        var decodedUrl = decodeURIComponent(req.originalUrl);
        req.originalUrl = decodedUrl;
    next();
});
var accessLogStream = fs.createWriteStream(path.join(__dirname, 'access.log'), { flags: 'a' })
app.use(morgan(':method :url :response-time'))
// respond with "hello world" when a GET request is made to the homepage
app.get("/test/*/id*", urlencodedParser, function (req, res) {

    let soapUIHeader = '<dummy></dummy>';
    setTimeout(function() {
        res.write('<div><p>Header........</p><div>');
        setTimeout(function body() {
            res.write('<div><p>Body........</p><div>');
            setTimeout(function footer() {
                res.write('<div><p>Footer........</p><div>');
                res.end();
            },3000)
        },3000);
    },3000)
});


app.listen(port, function() {
    console.log("server started in port " + port);
});

module.exports = app

1 个答案:

答案 0 :(得分:2)

启用响应流后,衡量响应时间的最佳方法是使用中间件。步骤如下:

在表达请求的开始处引入中间件函数setReqBeginTime。此函数捕获请求的当前时间并将其存储为请求标头(req.headers ['reqBeginTime'] = currentTime;)。在快速请求的末尾添加另一个函数logResponeEndTime。此函数通过减去reqBeginTime来获取请求的最终执行时间并获得响应时间。

希望这会有所帮助

let setReqBeginTime = (req, res, next) => {
	var currentTime = Date.now();
	req.headers['reqBeginTime'] = currentTime;
	next();
}

let logResponeEndTime = (req, res, next) => {
	var currentTime = Date.now();
	var reqBeginTime = req.headers['reqBeginTime'];
	var responseTime = currentTime - reqBeginTime;
	req.headers['respEndTime'] = responseTime;
	next();
}

app.get("/test/*/id*", setReqBeginTime(), urlencodedParser, function (req, res) {

    let soapUIHeader = '<dummy></dummy>';
    setTimeout(function() {
        res.write('<div><p>Header........</p><div>');
        setTimeout(function body() {
            res.write('<div><p>Body........</p><div>');
            setTimeout(function footer() {
                res.write('<div><p>Footer........</p><div>');
                res.end();
            },3000)
        },3000);
    },3000)
}, logResponeEndTime());