...

Source file src/go.mongodb.org/mongo-driver/internal/logger/context.go

Documentation: go.mongodb.org/mongo-driver/internal/logger

     1  // Copyright (C) MongoDB, Inc. 2023-present.
     2  //
     3  // Licensed under the Apache License, Version 2.0 (the "License"); you may
     4  // not use this file except in compliance with the License. You may obtain
     5  // a copy of the License at http://www.apache.org/licenses/LICENSE-2.0
     6  
     7  package logger
     8  
     9  import "context"
    10  
    11  // contextKey is a custom type used to prevent key collisions when using the
    12  // context package.
    13  type contextKey string
    14  
    15  const (
    16  	contextKeyOperation   contextKey = "operation"
    17  	contextKeyOperationID contextKey = "operationID"
    18  )
    19  
    20  // WithOperationName adds the operation name to the context.
    21  func WithOperationName(ctx context.Context, operation string) context.Context {
    22  	return context.WithValue(ctx, contextKeyOperation, operation)
    23  }
    24  
    25  // WithOperationID adds the operation ID to the context.
    26  func WithOperationID(ctx context.Context, operationID int32) context.Context {
    27  	return context.WithValue(ctx, contextKeyOperationID, operationID)
    28  }
    29  
    30  // OperationName returns the operation name from the context.
    31  func OperationName(ctx context.Context) (string, bool) {
    32  	operationName := ctx.Value(contextKeyOperation)
    33  	if operationName == nil {
    34  		return "", false
    35  	}
    36  
    37  	return operationName.(string), true
    38  }
    39  
    40  // OperationID returns the operation ID from the context.
    41  func OperationID(ctx context.Context) (int32, bool) {
    42  	operationID := ctx.Value(contextKeyOperationID)
    43  	if operationID == nil {
    44  		return 0, false
    45  	}
    46  
    47  	return operationID.(int32), true
    48  }
    49  

View as plain text