github.com/yankunsam/loki/v2@v2.6.3-0.20220817130409-389df5235c27/pkg/util/log/wrappers.go (about)

     1  package log
     2  
     3  import (
     4  	"context"
     5  
     6  	"github.com/go-kit/log"
     7  	"github.com/weaveworks/common/tracing"
     8  
     9  	"github.com/grafana/dskit/tenant"
    10  )
    11  
    12  // WithUserID returns a Logger that has information about the current user in
    13  // its details.
    14  func WithUserID(userID string, l log.Logger) log.Logger {
    15  	// See note in WithContext.
    16  	return log.With(l, "org_id", userID)
    17  }
    18  
    19  // WithContext returns a log.Logger that has information about the current user in
    20  // its details.
    21  //
    22  // e.g.
    23  //   log := util.WithContext(ctx)
    24  //   log.Errorf("Could not chunk chunks: %v", err)
    25  func WithContext(ctx context.Context, l log.Logger) log.Logger {
    26  	// Weaveworks uses "orgs" and "orgID" to represent Cortex users,
    27  	// even though the code-base generally uses `userID` to refer to the same thing.
    28  	userID, err := tenant.TenantID(ctx)
    29  	if err == nil {
    30  		l = WithUserID(userID, l)
    31  	}
    32  
    33  	traceID, ok := tracing.ExtractSampledTraceID(ctx)
    34  	if !ok {
    35  		return l
    36  	}
    37  
    38  	return log.With(l, "traceID", traceID)
    39  }