Skip to content

Instantly share code, notes, and snippets.

@arutnik
Created September 17, 2019 16:36
Show Gist options
  • Save arutnik/22dffb4a49cecbaba4dddb81d0a902f8 to your computer and use it in GitHub Desktop.
Save arutnik/22dffb4a49cecbaba4dddb81d0a902f8 to your computer and use it in GitHub Desktop.
ARR Node Js Instrumenting
const http = require('http');
const https = require('https');
function urlToOptions(url) {
const options = {
protocol: url.protocol,
hostname: typeof url.hostname === 'string' && url.hostname.startsWith('[') ?
url.hostname.slice(1, -1) :
url.hostname,
hash: url.hash,
search: url.search,
pathname: url.pathname,
path: `${url.pathname || ''}${url.search || ''}`,
href: url.href
};
if (url.port !== '') {
options.port = Number(url.port);
}
if (url.username || url.password) {
options.auth = `${url.username}:${url.password}`;
}
return options;
}
function wrapRequest(originalRequest, logger, clsNamespace) {
return function (...args) {
let reqOptions = {};
try {
if (typeof args[0] === 'string') {
const urlStr = args.shift();
reqOptions = urlToOptions(new URL(urlStr));
} else if (args[0] && typeof args[0] === 'object' &&
args[0].constructor && args[0].constructor.name === 'URL') {
// url.URL instance most likely
reqOptions = urlToOptions(args.shift());
}
if (args[0] && typeof args[0] !== 'function') {
//If after taking the first argument, there is a second arg that was a
//options object
Object.assign(reqOptions, args.shift());
}
if (!(typeof reqOptions.headers === 'object')) {
reqOptions.headers = {};
}
const branchHeaderValue = clsNamespace.get('header_mycomp_branch');
if (branchHeaderValue) {
Object.assign(reqOptions.headers, { mycomp_branch: branchHeaderValue });
}
args.unshift(reqOptions);
} catch (hex) {
logger.error(`Error instrumenting outbound http request ${reqOptions.host} ${hex.name} ${hex.message}`);
throw hex;
}
return originalRequest(...args);
}
}
const instrumentOutboundHttp = function (logger, clsNamespace) {
const httpRequest = http.request;
const httpsRequest = https.request;
http.request = wrapRequest(httpRequest, logger, clsNamespace);
https.request = wrapRequest(httpsRequest, logger, clsNamespace);
}
module.exports = instrumentOutboundHttp;
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment