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

Nodejs: Morgon logs are not logging complete response time when streaming is enabled

我有一个代码可以使用 nodejs 和 express 进行简单 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

启用响应流时测量响应时间的最佳方法是使用中间件。以下是步骤:

在express请求的开头引入一个中间件函数setReqBeginTime。该函数捕获请求的当前时间并存储为请求header (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());