@commercetools/ts-sdk-apm
Version:
commercetools typescript SDK application performance monitoring.
71 lines (62 loc) • 1.95 kB
JavaScript
import datadog from 'dd-trace';
// Initialize datadog once
datadog.init();
// Record metrics for datadog
const recordDatadog = (metric, tags) => {
datadog.dogstatsd.gauge(`client_response_time`, metric, tags);
};
const time = () => performance.now();
function createTelemetryMiddleware(options) {
/**
* default newrelic APM and
* opentelemetry tracer modules
*/
const defaultOptions = {
/**
* if this is to be used with newrelic, then
* pass this (apm) as an option in the `createTelemetryMiddleware`
* function e.g createTelemetryMiddleware({ apm: () => require('newrelic'), ... })
* Note: don't forget to install newrelic agent in your project `yarn add newrelic`
*/
apm: () => {},
tracer: () => import('./opentelemetry-8a97600d.esm.js')
};
// trace
function trace() {
// validate apm and tracer
if (!(options?.apm && typeof options.apm == 'function')) {
options.apm = defaultOptions.apm;
}
if (!(options?.tracer && typeof options.tracer == 'function')) {
options.tracer = defaultOptions.tracer;
}
options.apm();
options.tracer();
}
trace(); // expose tracing modules
return next => async request => {
const nextRequest = {
...request,
...options
};
// start (high resolution milliseconds) timestamp
const start = time();
const response = await next(nextRequest);
const response_time = time() - start;
// send `response_time` to APM platforms
if (options?.customMetrics && options.customMetrics.datadog) {
recordDatadog(response_time, {
env: process.env.NODE_ENV || 'dev'
});
}
if (options?.customMetrics && options.customMetrics.newrelic) {
// @ts-ignore
const {
recordNewRelic
} = await import('./newRelicHelper-86b0a261.esm.js');
recordNewRelic(response_time);
}
return response;
};
}
export { createTelemetryMiddleware };