要记录从 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')...