【问题标题】:Is there a way to get request and response body of a http request for a microservices application?有没有办法获取微服务应用程序的 http 请求的请求和响应正文?
【发布时间】:2018-11-16 00:26:48
【问题描述】:

我有一个由 2 个微服务组成的应用程序。

有没有一种方法可以让每个微服务接收和发送的每个请求都得到请求和响应,而代码更改最少。

应用程序位于 node.js 中。

我尝试了一些跟踪框架,但它们只提供时间信息。

【问题讨论】:

    标签: node.js microservices trace


    【解决方案1】:

    如果你使用 express 来实现你的 API 后端服务器,你可以使用 express-winston 来拦截每个调用的请求和响应。

    在下面的示例中,使用 express winston 将请求和响应注销到控制台。

    const winston = require('winston');
    const expressWinston = require('express-winston');
    
    /**
     * Custom Wiston Express Middleware to log all requests and responses in the console.
     */
    module.exports = async() => {
        // Creating middleware
        expressWinston.requestWhitelist.push('body');
        expressWinston.responseWhitelist.push('body');
        const wistonMiddleware = expressWinston.logger({
            transports: [
                new winston.transports.Console({
                    json: true,
                    colorize: true
                })
            ],
            // optional: control whether you want to log the meta data about the request (default to true)
            meta: true,
            // optional: customize the default logging message. E.g. "{{res.statusCode}} {{req.method}} {{res.responseTime}}ms {{req.url}}"
            msg: 'HTTP {{req.method}} {{req.url}}',
            // Use the default Express/morgan request formatting, with the same colors.
            // Enabling this will override any msg and colorStatus if true. Will only output colors on transports with colorize set to true
            expressFormat: true,
            // Color the status code, using the Express/morgan color palette (default green, 3XX cyan, 4XX yellow, 5XX red). Will not be recognized if expressFormat is true
            colorStatus: true,
            ignoreRoute: function (req, res) {
                return false;
            } // optional: allows to skip some log messages based on request and/or response
        });
    
        return wistonMiddleware;
    };
    

    但是,您可以让其他 winston 模块以不同的方式登录,例如弹性搜索:https://github.com/vanthome/winston-elasticsearch

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2018-02-02
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2018-08-04
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多