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

Pas*_*enn 1 graphql 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 的文章使用了 DefaultGraphQLExecuter - public class GraphQLExecutorWithDiagnostics<TSchema> : DefaultGraphQLExecuter<TSchema> 它在 中提供了一个 operationName 参数 Task<ExecutionResult> ExecuteAsync( ,这看起来很理想。

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

Pas*_*enn 5

您正在寻找的是DiagnosticEventListener

您只需扩展此基类并重写日志记录所需的方法即可。

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

    public virtual IActivityScope ResolveFieldValue(IMiddlewareContext context)
    {
        return EmptyScope;
    }
}
Run Code Online (Sandbox Code Playgroud)

要使用此诊断侦听器,您必须将其添加到架构中

services.AddGraphQLServer()
    ...
   .AddDiagnosticEventListener<CustomDiagnosticListener>()
Run Code Online (Sandbox Code Playgroud)

如果您有侦听器必须重新处理的依赖项,则必须手动重新处理它们:

services.AddGraphQLServer()
    ...
   .AddDiagnosticEventListener<CustomDiagnosticListener>(
         sp => new CustomDiagnosticListener(
                sp.GetApplicationService<MyDependency>()))
Run Code Online (Sandbox Code Playgroud)