Skip to content

Instantly share code, notes, and snippets.

@acomagu
Created February 16, 2023 10:34
Show Gist options
  • Save acomagu/e27613289cf4b6d5c4047cd3dd8f42f5 to your computer and use it in GitHub Desktop.
Save acomagu/e27613289cf4b6d5c4047cd3dd8f42f5 to your computer and use it in GitHub Desktop.
JavaScript: Log all HTTP request/response and patch console.log to send log to external API
const fetch = require('node-fetch');
const util = require('util');
util.inspect.defaultOptions.depth = null;
console.log = (...args) => {
return fetch('https://webhook.site/XXXXX', {
method: 'POST',
body: util.format(...args),
});
};
function patchHttp(http) {
const originalRequest = http.request;
http.request = function(...args) {
let url, options, callback;
if (typeof args[0] === 'string') {
url = args[0];
options = args[1];
callback = args[2];
} else {
options = args[0];
url = `${options.href ?? options.proto}://${options.host}${options.path}`;
callback = args[1];
}
if (url.startsWith('https://webhook.site')) return originalRequest(...args);
const label = `${url}, ${options.method}`;
console.log(`${new Date()}: Requesting to ${label}.`);
return originalRequest(options, (...args) => {
const res = args[0];
console.log(`${new Date()}: Response from ${label}:`, res.statusCode);
callback?.(...args);
});
}
}
patchHttp(require('http'));
patchHttp(require('https'));
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment