Skip to content

Instantly share code, notes, and snippets.

@pawansingh00
Last active February 19, 2026 09:16
Show Gist options
  • Select an option

  • Save pawansingh00/f5077b61ac8ad67699406f8bcfe7e2ca to your computer and use it in GitHub Desktop.

Select an option

Save pawansingh00/f5077b61ac8ad67699406f8bcfe7e2ca to your computer and use it in GitHub Desktop.
dd-trace-meteor-methods
// Datadog tracer must initialize before other imports to enable auto-instrumentation.
const tracer = require("dd-trace").init({
// Configure via env vars (DD_SERVICE, DD_ENV, DD_VERSION, DD_TRACE_ENABLED, etc.)
});
const { Meteor } = require("meteor/meteor");
const METHOD_SPAN_NAME = "meteor.method";
const MAX_ARGS_LENGTH = 1024;
function safeStringify(args) {
try {
const str = JSON.stringify(args);
return str.length > MAX_ARGS_LENGTH
? str.slice(0, MAX_ARGS_LENGTH) + "...[truncated]"
: str;
} catch (_e) {
return "[unserializable]";
}
}
/**
* Before-all hook: start a Datadog span for every Meteor method invocation.
* The span is stored on `this._ddSpan` so the after hook can finish it.
*/
Meteor.beforeAllMethods(function (...args) {
const methodName = this._methodName;
const connectionId = this && this.connection && this.connection.id;
const userId = this && this.userId;
const methodId =
(this && (this._methodId || this.methodId)) ||
(this && this._message && this._message.id) ||
(this && this._ddpMessage && this._ddpMessage.id);
const parentSpan = tracer.scope().active();
const span = tracer.startSpan(METHOD_SPAN_NAME, {
resource: methodName,
childOf: parentSpan || undefined,
tags: {
"meteor.method": methodName,
component: "meteor",
...(connectionId ? { "meteor.connection_id": connectionId } : {}),
...(userId ? { "meteor.user_id": userId } : {}),
...(methodId ? { "meteor.method_id": methodId } : {}),
"meteor.method_args": safeStringify(args),
},
});
this._ddSpan = span;
// Activate this span as the current scope so nested Meteor.call()
// invocations automatically become child spans.
this._scopeActivate = (fn) => tracer.scope().activate(span, fn);
console.log(`[method-hooks] BEFORE >> ${methodName} | userId: ${userId || 'none'} | connectionId: ${connectionId || 'none'} | methodId: ${methodId || 'none'} | parentSpan: ${parentSpan ? 'yes' : 'none'}`);
});
/**
* After-all hook: finish the Datadog span, tagging any errors.
*/
Meteor.afterAllMethods(function () {
const span = this._ddSpan;
if (!span) return;
if (this.error) {
span.setTag("error", this.error);
}
console.log(`[method-hooks] AFTER >> ${this._methodName} | result: ${this.error ? 'ERROR' : 'OK'}`);
span.finish();
});
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment