【问题标题】:Tracking and logging http calls made internally from a node.js server跟踪和记录从 node.js 服务器内部进行的 http 调用
【发布时间】:2018-02-21 11:20:54
【问题描述】:

我正在调试从我的 express 应用程序对我网络上另一个微服务的调用。我收到 401 错误,我需要获取完整的原始 http 日志以提供给我的安全团队进行分析。

我正在寻找一些关于跟踪来自我在 Pivotal Cloud Foundry 上部署的微服务的 HTTP 调用的建议。我一直在做一些研究,并遇到过 Zipkin 和 OpenTracing 等工具。但这些似乎更多的是关于调试延迟,可能不显示 HTTP 日志。我也尝试过使用 Morgan/Winston 模块,但它们不跟踪内部呼叫。 Morgan 目前是我用来注销基本 HTTP 代码的工具,但它也不会从我的应用程序内部接听我的调用,只是从浏览器对应用程序本身进行的调用。我需要获取完整的原始 HTTP 请求以协助安全团队。我正在使用带有 morgan (STDOUT) 的默认日志记录输出。我已经通过控制台记录了标头以查看标头,但希望以更易读的格式显示它们。

【问题讨论】:

    标签: node.js http logging cloud microservices


    【解决方案1】:

    要记录从 Node.js 服务器发送的内部 HTTP 请求,您可以创建一个代理 Node.js 服务器并使用 Morgan 记录那里的所有请求。

    首先,定义 3 个常量(或从您的项目配置文件中读取):

    // The real API endpoint, such as "another micro-service" in your network
    const API = http://<real_server>
    // Proxy Node.js server running on localhost
    const LOGGER_ENDPOINT=http://localhost:3010
    // Flag, decide whether logger is enabled.
    const ENABLE_LOGGER=true
    

    其次,当你的 Node.js 服务器启动时,如果ENABLE_LOGGER 为真,则同时启动记录器服务器。记录器服务器只做一件事:记录请求并使用request 模块将其转发到真正的API 服务器。您可以使用Morgan 提供更易读的格式。

    const request = require('request');
    const morgan = require('morgan')(':method :url :status Cookie: :req[Cookie] :res[content-length] - :response-time ms');
    ...
    if (ENABLE_LOGGER && LOGGER_ENDPOINT) {
      let loggerPort = 3010;
      const logger = http.createServer((req, res) => {
        morgan(req, res, () => {
          req.pipe(request(API + req.url)).pipe(res);
        });
      });
      logger.listen(loggerPort);
    }
    

    第三,在你的Node.js服务器中,ENABLE_LOGGER为真时向logger服务器发送API请求,ENABLE_LOGGER为false时直接向真实服务器发送API。

    let app = express(); // assume Express is used, but this strategy can be easily applied to other Node.js web framework.
    ...
    let API_Endpoint = ENABLE_LOGGER ? LOGGER_ENDPOINT : API;
    app.set('API', API_Endpoint);
    ...
    // When HTTP request is sent internally
    request(app.get('API') + '/some-url')... 
    

    【讨论】:

    • 非常感谢@shaochuancs 的回复。这正是我需要的:)
    猜你喜欢
    • 1970-01-01
    • 2021-06-03
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2020-03-13
    相关资源
    最近更新 更多