要记录从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服务器,发送API请求记录服务器时ENABLE_LOGGER
是真实的,并直接发送API到真实服务器时ENABLE_LOGGER
是假的。
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。这正是我需要的:) –