GraphQL + Spring Boot:如何收集(错误)指标?

GraphQL + Spring Boot: how to collect (error) metrics?

我最近一直致力于在我们的 GraphQL 网关中添加监控指标。

我们正在为网关使用 graphql-spring-boot 启动器。

阅读以下文档后,我设法将基本 graphql.timer.query.* 指标发送给 Datadog

到目前为止,我所取得的成就是,当我发送 GraphQL query/mutation 时,我会相应地收集请求计数和时间。例如发送下面的查询

query HelloWorldQuery {
  greeting(
    name: "Bob"
  ) {
    message
  }
}

我会看到带有标签 operationName=HelloWorldQuery

的指标 graphql.timer.query.count / graphql.timer.query.sum

它工作得非常完美,直到我想测试一个有错误的查询。我意识到没有 metrics/tags 与失败的查询相关。例如,如果我在上面查询 returns 空数据和一些 GraphQL 错误,我仍然会收集 graphql.timer.query.count (operationName=HelloWorldQuery),但没有额外的标签让我告诉我该查询有错误。

在网关中,我实现了自定义 GraphQLErrorHandler,所以我在想也许我应该在 class 中添加错误计数器(通过 MeterRegistry),但我无法获得 operationName 简单地来自 GraphQLError 类型。我能得到的最好的是 error.getPath() 它给出了方法名称(例如 greeting)而不是自定义查询名称(HelloWorldQuery - 与 graphql.timer.query.* 提供的一致).

我的问题是,如何解决上面的问题? 通常收集 GraphQL 查询指标(包括错误)的最佳方式是什么?

-------------------- 更新 -------------- ----

2019-12-31 我在 graphql-spring-boot repo 中阅读了更多关于 GraphQL Instrumentation here and checked the MetricsInstrumentation 实现的信息,我想通过在其中添加错误指标来扩展 MetricsInstrumentation class。

2020-01-02 我试图摄取我的 CustomMetricsInstrumentation class,但没有成功。有内部自动配置接线,我不能在中间插入我的自动配置。

您可以使用自己的实现覆盖默认 TracingInstrumentation。由于 GraphQLInstrumentationAutoConfiguration class 中的 @ConditionalOnMissingBean 注释,它将被自动选取。这是一个添加两个自定义指标的简单示例:graphql.counter.query.successgraphql.counter.query.error:

@Component
public class CustomMetricsInstrumentation extends TracingInstrumentation {

    private static final String QUERY_STATUS_COUNTER_METRIC_NAME = "graphql.counter.query";
    private static final String OPERATION_NAME_TAG = "operationName";
    private static final String UNKNOWN_OPERATION_NAME = "unknown";

    private MeterRegistry meterRegistry;

    public CustomMetricsInstrumentation(MeterRegistry meterRegistry) {
        this.meterRegistry = meterRegistry;
    }

    @Override
    public CompletableFuture<ExecutionResult> instrumentExecutionResult(ExecutionResult executionResult,
                                                                        InstrumentationExecutionParameters parameters) {

        String status = CollectionUtils.isEmpty(executionResult.getErrors()) ? "success" : "error";
        String operation = parameters.getOperation() != null ? parameters.getOperation() : UNKNOWN_OPERATION_NAME;
        Collection<Tag> tags = Arrays.asList(Tag.of(OPERATION_NAME_TAG, operation));

        meterRegistry.counter(QUERY_STATUS_COUNTER_METRIC_NAME + "." + status, tags).increment();

        return super.instrumentExecutionResult(executionResult, parameters);
    }
}

我的application.yaml,以防万一:

graphql:
  servlet:
    tracing-enabled: true
    actuator-metrics: true
management:
  endpoint:
  metrics:
    enabled: true
  endpoints:
    web:
      exposure:
        include: health,metrics

我正在使用 spring-boot-starter-parent:2.2.2.RELEASE, graphql-spring-boot-starter:6.0.0

希望对您有所帮助。