github.com/kyma-incubator/compass/components/director@v0.0.0-20230623144113-d764f56ff805/pkg/log/gql_ops_logger.go (about)

     1  package log
     2  
     3  import (
     4  	"context"
     5  
     6  	"github.com/99designs/gqlgen/graphql"
     7  	"github.com/vektah/gqlparser/v2/ast"
     8  )
     9  
    10  const (
    11  	logKeyOperationType string = "gql-op-type"
    12  	logKeySelectionSet  string = "gql-operation"
    13  )
    14  
    15  // NewGqlLoggingInterceptor creates a new opsInterceptor instance
    16  func NewGqlLoggingInterceptor() *opsInterceptor {
    17  	return &opsInterceptor{}
    18  }
    19  
    20  type opsInterceptor struct {
    21  }
    22  
    23  func (m *opsInterceptor) ExtensionName() string {
    24  	return "Logging Interceptor"
    25  }
    26  
    27  func (m *opsInterceptor) Validate(_ graphql.ExecutableSchema) error {
    28  	return nil
    29  }
    30  
    31  func (m *opsInterceptor) InterceptOperation(ctx context.Context, next graphql.OperationHandler) graphql.ResponseHandler {
    32  	if mdc := MdcFromContext(ctx); nil != mdc {
    33  		opsCtx := graphql.GetOperationContext(ctx)
    34  		mdc.Set(logKeyOperationType, string(opsCtx.Operation.Operation))
    35  
    36  		selectionSet := ""
    37  		for _, selection := range opsCtx.Operation.SelectionSet {
    38  			if field, ok := selection.(*ast.Field); ok {
    39  				if len(selectionSet) != 0 {
    40  					selectionSet += ","
    41  				}
    42  
    43  				selectionSet += field.Name
    44  			}
    45  		}
    46  		mdc.Set(logKeySelectionSet, selectionSet)
    47  	}
    48  
    49  	return next(ctx)
    50  }