1

我正在使用弹性 APM。我发现当以某种方式与 GraphQL/Apollo Server 一起使用时,mongoose 集成不起作用。我写了一个这样的 apollo-server 插件来启动/停止事务:

import apm from 'elastic-apm-node/start';
import _ from 'lodash';
import { gql } from 'apollo-server-express';

const apmPlugin = {
  requestDidStart: (requestContext) => {
    const query = gql`${requestContext.request.query}`;
    const type = _.get(query, 'definitions[0].operation', '');
    const funcName = _.get(query, 'definitions[0].name.value', '');
    const txnName = type && funcName ? `${type} ${funcName}` : '/gql';
    const txn = apm.startTransaction(txnName, 'graphql');
    return {
      didEncounterErrors: (err) => {
        if (txn) {
          txn.result = err.errors.length === 1 ? err.errors[0].name : 'error';
        }
      },

      willSendResponse: (res) => {
        if (Array.isArray(res.response.errors).length === 0) {
          txn.result = 'success';
        }
        if (typeof txn?.end === 'function') txn.end();
      },
    };
  },
};

它有效,但是我缺少猫鼬的跨度,当我启用跟踪时,这就是我所看到的:

start trace {
  trans: 'ddc03cb86cf71448',
  parent: undefined,
  trace: '7127e63abe8e6d5086d36c13deee8183',
  name: 'unnamed',
  type: 'graphql',
  subtype: null,
  action: null
}
start span {
  span: '94fc2307e19dd187',
  parent: 'ddc03cb86cf71448',
  trace: '7127e63abe8e6d5086d36c13deee8183',
  name: 'GraphQL: Unknown Query',
  type: 'db',
  subtype: 'graphql',
  action: 'execute'
}
intercepted call to graphql.execute { id: 'ddc03cb86cf71448' }
Mongoose: yyy.findOne({ domainSlug: 'xxx' }, { projection: {} })
no active transaction found - cannot build new span
Mongoose: yyy.findOne({ email: 'xxx', company: ObjectId("5f1ab19010469e8eb952e754") }}, { projection: {} })
no active transaction found - cannot build new span
Mongoose: roles.find({ _id: { '$in': [ ObjectId("5f1ab19010469e8eb952e786") ] } }, { skip: undefined, limit: undefined, perDocumentLimit: undefined, projection: {}})
no active transaction found - cannot build new span
ended span {
  span: '94fc2307e19dd187',
  parent: 'ddc03cb86cf71448',
  trace: '7127e63abe8e6d5086d36c13deee8183',
  name: 'GraphQL: xxx',
  type: 'db',
  subtype: 'graphql',
  action: 'execute'
}
encoding span {
  span: '94fc2307e19dd187',
  parent: 'ddc03cb86cf71448',
  trace: '7127e63abe8e6d5086d36c13deee8183',
  name: 'GraphQL: xxx',
  type: 'db'
}
sending span {
  span: '94fc2307e19dd187',
  parent: 'ddc03cb86cf71448',
  trace: '7127e63abe8e6d5086d36c13deee8183',
  name: 'GraphQL: xxx',
  type: 'db'
}
sending transaction {
  trans: 'ddc03cb86cf71448',
  trace: '7127e63abe8e6d5086d36c13deee8183'
}
ended transaction {
  trans: 'ddc03cb86cf71448',
  parent: undefined,
  trace: '7127e63abe8e6d5086d36c13deee8183',
  type: 'graphql',
  result: 'success',
  name: 'mutation doLogin'
}

请注意,在这些 mongoose 调用之前和之后创建的跨度很好,但是 mongoose 调用似乎无法以某种方式找到活动事务。

no active transaction found - cannot build new span

4

0 回答 0