如何在 HotChocolate 中记录 resolver/operation 名称和持续时间?

How can I log resolver/operation name and duration in HotChocolate?

我正在尝试记录一些基本的 gql 方法详细信息 - resolver/operation 名称和持续时间。 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> 它在 Task<ExecutionResult> ExecuteAsync( ,看起来很理想。

我将登录到 AppInsights,但目前与此无关,我只想先获取信息。 我正在使用 v11.0.8

您要找的是 DiagnosticEventListener

您可以只扩展此基础 class 并覆盖您记录所需的方法。

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>()))