如何在HotChocolate中记录解析器/操作名称和持续时间?



我正在尝试记录一些基本的gql方法细节-解析器/操作名称和持续时间。I've started looking at using .AddHttpRequestInterceptor((context, executor, builder, ct)并从构建器中获取信息,但即使我可以在调试器中看到它,方法名称也被隐藏在私有成员中,如:((HotChocolate.Execution.QueryRequestBuilder)builder)._query.Document.Definitions[0].SelectionSet.Selections[0].Name.Value

我相信有一个更简单和更好的方法来挂钩到管道来获取方法名并记录调用持续时间。

我找到一篇关于GraphQL的文章。. Net使用DefaultGraphQLExecuterpublic class GraphQLExecutorWithDiagnostics<TSchema> : DefaultGraphQLExecuter<TSchema>在?中提供operationName参数Task<ExecutionResult> ExecuteAsync(,看起来很理想。

我将登录到AppInsights,但这与现在无关,我只想先获得信息。我使用的是v11.0.8

你要找的是DiagnosticEventListener

你可以扩展这个基类并覆盖你需要的日志记录方法。

public class CustomDiagnosticListener : DiagnosticEventListener
{
public override IActivityScope ExecuteRequest(IRequestContext context)
{
return EmptyScope;
}
public virtual IActivityScope ResolveFieldValue(IMiddlewareContext context)
{
return EmptyScope;
}
}

要使用此诊断侦听器,必须将其添加到模式

services.AddGraphQLServer()
...
.AddDiagnosticEventListener<CustomDiagnosticListener>()

如果你有依赖,你的监听器必须解决,你必须手动解决它们:

services.AddGraphQLServer()
...
.AddDiagnosticEventListener<CustomDiagnosticListener>(
sp => new CustomDiagnosticListener(
sp.GetApplicationService<MyDependency>()))

最新更新