Span.prototype._encode = function()

in lib/instrumentation/span.js [458:570]


Span.prototype._encode = function (cb) {
  var self = this;

  if (!this.ended) {
    return cb(new Error('cannot encode un-ended span'));
  }

  const payload = {
    id: self.id,
    transaction_id: self.transaction.id,
    parent_id: self.parentId,
    trace_id: self.traceId,
    name: self.name,
    type: self.type || constants.DEFAULT_SPAN_TYPE,
    subtype: self.subtype,
    action: self.action,
    timestamp: self.timestamp,
    duration: self._duration,
    context: undefined,
    stacktrace: undefined,
    sync: self.sync,
    outcome: self.outcome,
  };

  // if a valid sample rate is set (truthy or zero), set the property
  const sampleRate = self.sampleRate;
  if (sampleRate !== null) {
    payload.sample_rate = sampleRate;
  }

  let haveContext = false;
  const context = {};
  if (self._serviceTarget) {
    context.service = { target: self._serviceTarget };
    haveContext = true;
  }
  if (self._destination) {
    context.destination = self._destination;
    haveContext = true;
  }
  if (self._db) {
    context.db = self._db;
    haveContext = true;
  }
  if (self._message) {
    context.message = self._message;
    haveContext = true;
  }
  if (self._http) {
    context.http = self._http;
    haveContext = true;
  }
  if (self._labels) {
    context.tags = self._labels;
    haveContext = true;
  }
  if (haveContext) {
    payload.context = context;
  }

  if (self.isComposite()) {
    payload.composite = self._compression.encode();
    payload.timestamp = self._compression.timestamp;
    payload.duration = self._compression.duration;
  }

  this._serializeOTel(payload);

  if (this._links.length > 0) {
    payload.links = this._links;
  }

  if (this._stackObj) {
    this._stackObj.then(
      (value) => done(null, value),
      (error) => done(error),
    );
  } else {
    process.nextTick(done);
  }

  function done(err, frames) {
    if (err) {
      self._agent.logger.debug('could not capture stack trace for span %o', {
        span: self.id,
        parent: self.parentId,
        trace: self.traceId,
        name: self.name,
        type: self.type,
        subtype: self.subtype,
        action: self.action,
        err: err.message,
      });
    } else if (frames) {
      payload.stacktrace = frames;
    }

    // Reduce this span's memory usage by dropping references once they're
    // no longer needed.  We also keep fields required to support
    // `interface Span`.
    // Span fields:
    self._db = null;
    self._http = null;
    self._message = null;
    self._capturedStackTrace = null;
    // GenericSpan fields:
    // - Cannot drop `this._context` because it is used for traceparent and ids.
    self._timer = null;
    self._labels = null;

    cb(null, payload);
  }
};