From 637cafda377c8e87180f79247242e0d14aac0238 Mon Sep 17 00:00:00 2001 From: darkskygit Date: Sat, 8 Mar 2025 16:39:07 +0000 Subject: [PATCH] feat(server): improve gql measure (#10706) --- .../server/src/base/graphql/logger-plugin.ts | 27 ++++++++++++++++--- 1 file changed, 23 insertions(+), 4 deletions(-) diff --git a/packages/backend/server/src/base/graphql/logger-plugin.ts b/packages/backend/server/src/base/graphql/logger-plugin.ts index 15e2f1d37..e41eec826 100644 --- a/packages/backend/server/src/base/graphql/logger-plugin.ts +++ b/packages/backend/server/src/base/graphql/logger-plugin.ts @@ -4,6 +4,7 @@ import { GraphQLRequestListener, } from '@apollo/server'; import { Plugin } from '@nestjs/apollo'; +import { Logger } from '@nestjs/common'; import { Response } from 'express'; import { metrics } from '../metrics/metrics'; @@ -17,13 +18,31 @@ export interface RequestContext { @Plugin() export class GQLLoggerPlugin implements ApolloServerPlugin { + private readonly logger = new Logger(GQLLoggerPlugin.name); + requestDidStart( ctx: GraphQLRequestContext ): Promise>> { const res = ctx.contextValue.req.res as Response; - const operation = ctx.request.operationName; + const headers = ctx.request.http?.headers; - metrics.gql.counter('query_counter').add(1, { operation }); + const info = { + operation: ctx.request.operationName, + clientVersion: headers?.get('x-affine-version'), + }; + + if (!info.operation) { + this.logger.warn( + `GraphQL operation name is not provided (${JSON.stringify({ + userAgent: headers?.get('user-agent'), + clientVersion: info.clientVersion, + rayId: headers?.get('cf-ray'), + country: headers?.get('cf-ipcountry'), + })})` + ); + } + + metrics.gql.counter('query_counter').add(1, info); const start = Date.now(); function endTimer() { return Date.now() - start; @@ -33,7 +52,7 @@ export class GQLLoggerPlugin implements ApolloServerPlugin { willSendResponse: () => { const time = endTimer(); res.setHeader('Server-Timing', `gql;dur=${time};desc="GraphQL"`); - metrics.gql.histogram('query_duration').record(time, { operation }); + metrics.gql.histogram('query_duration').record(time, info); return Promise.resolve(); }, didEncounterErrors: ctx => { @@ -42,7 +61,7 @@ export class GQLLoggerPlugin implements ApolloServerPlugin { error.log('GraphQL'); metrics.gql.counter('query_error_counter').add(1, { - operation, + ...info, code: error.status, type: error.type, error: error.name,