【问题标题】:How to add instrumentation to GraphQL Java with graphql-spring-boot?如何使用 graphql-spring-boot 向 GraphQL Java 添加检测?
【发布时间】:2020-05-16 04:49:40
【问题描述】:
【问题讨论】:
标签:
java
spring-boot
graphql
【解决方案1】:
有一种更简单的方法可以通过 spring boot 添加检测:
@Configuration
public class InstrumentationConfiguration {
@Bean
public Instrumentation someFieldCheckingInstrumentation() {
return new FieldValidationInstrumentation(env -> {
// ...
});
}
}
Spring boot 将收集所有实现 Instrumentation 的 bean(参见 GraphQLWebAutoConfiguration)。
【解决方案2】:
回答我自己的问题。与此同时,我设法做到了:
final class RequestLoggingInstrumentation extends SimpleInstrumentation {
private static final Logger logger = LoggerFactory.getLogger(RequestLoggingInstrumentation.class);
@Override
public InstrumentationContext<ExecutionResult> beginExecution(InstrumentationExecutionParameters parameters) {
long startMillis = System.currentTimeMillis();
var executionId = parameters.getExecutionInput().getExecutionId();
if (logger.isInfoEnabled()) {
logger.info("GraphQL execution {} started", executionId);
var query = parameters.getQuery();
logger.info("[{}] query: {}", executionId, query);
if (parameters.getVariables() != null && !parameters.getVariables().isEmpty()) {
logger.info("[{}] variables: {}", executionId, parameters.getVariables());
}
}
return new SimpleInstrumentationContext<>() {
@Override
public void onCompleted(ExecutionResult executionResult, Throwable t) {
if (logger.isInfoEnabled()) {
long endMillis = System.currentTimeMillis();
if (t != null) {
logger.info("GraphQL execution {} failed: {}", executionId, t.getMessage(), t);
} else {
var resultMap = executionResult.toSpecification();
var resultJSON = ObjectMapper.pojoToJSON(resultMap).replace("\n", "\\n");
logger.info("[{}] completed in {}ms", executionId, endMillis - startMillis);
logger.info("[{}] result: {}", executionId, resultJSON);
}
}
}
};
}
}
@Service
class InstrumentationService {
private final ContextFactory contextFactory;
InstrumentationService(ContextFactory contextFactory) {
this.contextFactory = contextFactory;
}
/**
* Return all instrumentations as a bean.
* The result will be used in class {@link com.oembedler.moon.graphql.boot.GraphQLWebAutoConfiguration}.
*/
@Bean
List<Instrumentation> instrumentations() {
// Note: Due to a bug in GraphQLWebAutoConfiguration, the returned list has to be modifiable (it will be sorted)
return new ArrayList<>(
List.of(new RequestLoggingInstrumentation()));
}
}
它帮助我了解了GraphQLWebAutoConfiguration 课程。在那里我发现框架需要一个 List<Instrumentation> 类型的 bean,其中包含将添加到 GraphQL 执行的所有工具。