Created
March 11, 2022 14:25
-
-
Save Gipphe/96d15b4cd5d69e06b3d442477d72c0d4 to your computer and use it in GitHub Desktop.
Log http requests
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
function enableRequestLogger() { | |
const https = require("https"); | |
const original = https.request; | |
https.request = function (options, callback) { | |
console.log( | |
new Date().toISOString(), | |
options.method, | |
options.protocol, | |
`${options.hostname}${options.path}` | |
); | |
console.log(options.headers); | |
// return original(options, callback); | |
const req = original(options, (res, ...rest) => { | |
const respBuffer = []; | |
res.on("data", (chunk) => { | |
respBuffer.push(chunk); | |
}); | |
res.on("end", () => { | |
const resp = Buffer.concat(respBuffer); | |
console.log(`Response: ${resp}`); | |
}); | |
callback(res, ...rest); | |
}); | |
const respBuffer = []; | |
req.on("data", (chunk) => { | |
respBuffer.push(chunk); | |
}); | |
req.on("end", () => { | |
const resp = Buffer.concat(respBuffer); | |
console.log(`Response: ${resp}`); | |
}); | |
const originalWrite = req.write; | |
req.write = (...args) => { | |
console.log(`Write: ${args}`); | |
return originalWrite.call(req, ...args); | |
}; | |
const originalEnd = req.end; | |
req.end = (...args) => { | |
return originalEnd.call(req, ...args); | |
}; | |
return req; | |
}; | |
} | |
enableRequestLogger(); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment