【发布时间】:2021-12-05 21:19:03
【问题描述】:
我在互联网上搜索了一个实现 apollo-server-express 跟踪但没有成功的示例。
我正在尝试在 apollo introspective playground 中启用跟踪,但是,我已经使用自定义插件实现“手动”添加了时间,但我在想这是否是最佳实践?内省显示请求的时间错误,这也不确定为什么!
这是我的插件。这个插件也使用哨兵进行性能跟踪。 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