我在网上搜索了一个实现apollo-server-express
跟踪但没有成功的例子。
我试图在阿波罗内省游乐场启用跟踪,但是,我已经"手动"管理了。增加使用自定义插件实现的时间,但在考虑这是否是最佳实践?内省显示了错误的请求时间,这也不确定为什么!
这是我的插件。这个插件也使用哨兵进行性能跟踪。Sentry工作得很好,但是我们需要更快的东西来开发。
/**
* To read more about apollo server plugins @see https://www.apollographql.com/docs/apollo-server/v2/integrations/plugins/
* */
import {
ApolloServerPlugin,
GraphQLFieldResolverParams,
GraphQLRequestContextWillSendResponse,
GraphQLRequestListener,
} from 'apollo-server-plugin-base';
import {Context} from '../models';
const sentryPlugin: ApolloServerPlugin<Context> = {
async requestDidStart({
request,
context,
}): Promise<GraphQLRequestListener<Context>> {
const startTime = new Date().getTime();
if (request.operationName)
context.sentryTransaction.setName(request.operationName!);
return {
async executionDidStart() {
return {
willResolveField(
reqContext: GraphQLFieldResolverParams<any, Context>
) {
// hook for each new resolver
const span = reqContext.context.sentryTransaction.startChild({
op: 'resolver',
description: `${reqContext.info.parentType.name}.${reqContext.info.fieldName}`,
});
return () => {
// this will execute once the resolver is finished
span.finish();
};
},
};
},
async willSendResponse(
requestContext: GraphQLRequestContextWillSendResponse<Context>
) {
const endTime = new Date().getTime();
requestContext.response.extensions = {
...requestContext.response.extensions,
tracing: {
version: 1,
startTime: new Date(startTime).toISOString(),
endTime: new Date(endTime).toISOString(),
duration: endTime - startTime, // <<== the time here is correct but introspective show it wrong!!
execution: {
resolvers: [], // <<=== This array is for each field. I'm sure that should not be manually implemented therefor I left it empty.
},
},
};
// hook for transaction finished
requestContext.context.sentryTransaction.finish();
},
};
},
};
export default sentryPlugin;
如果这是apollo-server-express@2.x(从代码上面的注释中猜测),我相信您只需要传递"tracing: true":
const server = new ApolloServer({
...otherConfig,
tracing: true
})
我也见过一些
的例子new ApolloServer({
plugins: [
require('apollo-tracing').plugin()
]
})