atatus-nodejs
Version:
Atatus APM agent for Node.js
49 lines (42 loc) • 1.29 kB
JavaScript
const shimmer = require('../shimmer.js');
// Helper to stringify any argument safely
function safeStringify(arg) {
try {
if (typeof arg === 'string') return arg;
if (arg instanceof Error) return ''
return JSON.stringify(arg);
} catch (err) {
return '[unserializable]';
}
}
let instrumented = false;
module.exports = {
instrument: function (agent) {
if (!instrumented) {
agent.logger.debug('Instrumenting console.error');
shimmer.wrap(console, 'error', function (original) {
return function (...args) {
const errorArg = args.find((arg) => arg instanceof Error);
const message = args.map((arg) => safeStringify(arg)).join(' ');
if (errorArg) {
agent.captureError(errorArg, { message });
} else {
// If no Error instance, capture with only a message
agent.captureError(message);
}
return original.apply(this, args);
};
});
instrumented = true;
} else {
agent.logger.debug('Already Instrumented console.error');
}
},
uninstrument: function () {
if (instrumented) {
agent.logger.debug('uninstrumenting console.error');
shimmer.unwrap(console, 'error');
instrumented = false
}
},
};