refactor(server): standarderlize metrics and trace with OTEL (#5054)
you can now export span to Zipkin and metrics to Prometheus when developing locally follow the docs of OTEL: https://opentelemetry.io/docs/instrumentation/js/exporters/ <img width="2357" alt="image" src="https://github.com/toeverything/AFFiNE/assets/8281226/ec615e1f-3e91-43f7-9111-d7d2629e9679">
This commit is contained in:
@@ -7,40 +7,39 @@ import { Plugin } from '@nestjs/apollo';
|
||||
import { Logger } from '@nestjs/common';
|
||||
import { Response } from 'express';
|
||||
|
||||
import { Metrics } from '../metrics/metrics';
|
||||
import { metrics } from '../metrics/metrics';
|
||||
import { ReqContext } from '../types';
|
||||
|
||||
@Plugin()
|
||||
export class GQLLoggerPlugin implements ApolloServerPlugin {
|
||||
protected logger = new Logger(GQLLoggerPlugin.name);
|
||||
|
||||
constructor(private readonly metrics: Metrics) {}
|
||||
|
||||
requestDidStart(
|
||||
reqContext: GraphQLRequestContext<ReqContext>
|
||||
): Promise<GraphQLRequestListener<GraphQLRequestContext<ReqContext>>> {
|
||||
const res = reqContext.contextValue.req.res as Response;
|
||||
const operation = reqContext.request.operationName;
|
||||
|
||||
this.metrics.gqlRequest(1, { operation });
|
||||
const timer = this.metrics.gqlTimer({ operation });
|
||||
metrics().gqlRequest.add(1, { operation });
|
||||
const start = Date.now();
|
||||
|
||||
return Promise.resolve({
|
||||
willSendResponse: () => {
|
||||
const costInMilliseconds = timer() * 1000;
|
||||
const costInMilliseconds = Date.now() - start;
|
||||
res.setHeader(
|
||||
'Server-Timing',
|
||||
`gql;dur=${costInMilliseconds};desc="GraphQL"`
|
||||
);
|
||||
metrics().gqlTimer.record(costInMilliseconds, { operation });
|
||||
return Promise.resolve();
|
||||
},
|
||||
didEncounterErrors: () => {
|
||||
this.metrics.gqlError(1, { operation });
|
||||
const costInMilliseconds = timer() * 1000;
|
||||
const costInMilliseconds = Date.now() - start;
|
||||
res.setHeader(
|
||||
'Server-Timing',
|
||||
`gql;dur=${costInMilliseconds};desc="GraphQL ${operation}"`
|
||||
);
|
||||
metrics().gqlTimer.record(costInMilliseconds, { operation });
|
||||
return Promise.resolve();
|
||||
},
|
||||
});
|
||||
|
||||
Reference in New Issue
Block a user