要記錄從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。這正是我需要的:) –