Skip to main content

Overview

Context helper functions allow you to extract metadata (trace IDs, span IDs, request IDs, user IDs) from Go contexts. These functions return empty strings if the metadata is not present in the context.

Functions

GetTraceID

Extracts the trace ID from the context.
func GetTraceID(ctx context.Context) string
Parameters:
  • ctx - The context to extract from
Returns:
  • The trace ID if set, or empty string
Example:
traceID := go_logs.GetTraceID(ctx)
if traceID != "" {
    logger.Info("Processing with trace", go_logs.String("trace_id", traceID))
}
Source Reference: context.go:106-129

GetSpanID

Extracts the span ID from the context.
func GetSpanID(ctx context.Context) string
Parameters:
  • ctx - The context to extract from
Returns:
  • The span ID if set, or empty string
Example:
spanID := go_logs.GetSpanID(ctx)
if spanID != "" {
    fmt.Printf("Current span: %s\n", spanID)
}
Source Reference: context.go:131-147

GetRequestID

Extracts the request ID from the context.
func GetRequestID(ctx context.Context) string
Parameters:
  • ctx - The context to extract from
Returns:
  • The request ID if set, or empty string
Example:
requestID := go_logs.GetRequestID(ctx)
if requestID != "" {
    fmt.Printf("Processing request: %s\n", requestID)
}
Source Reference: context.go:149-165

GetUserID

Extracts the user ID from the context.
func GetUserID(ctx context.Context) string
Parameters:
  • ctx - The context to extract from
Returns:
  • The user ID if set, or empty string
Example:
userID := go_logs.GetUserID(ctx)
if userID != "" {
    fmt.Printf("Current user: %s\n", userID)
}
Source Reference: context.go:167-183

ExtractFieldsFromContext

Extracts all structured fields from the context.
func ExtractFieldsFromContext(ctx context.Context) []Field
Parameters:
  • ctx - The context to extract from
Returns:
  • A slice of Field structs containing the extracted context values
Description: This function automatically extracts trace_id, span_id, request_id, and user_id from the context and returns them as Field structs. This is used internally by LogCtx to automatically include context information in log entries. Example:
fields := go_logs.ExtractFieldsFromContext(ctx)
// fields may contain: String("trace_id", "..."), String("span_id", "..."), etc.

logger.Info("Processing request", fields...)
Internal Usage: This function is automatically called by context-aware logging methods:
// Inside LogCtx implementation
func (l *LoggerImpl) LogCtx(ctx context.Context, level Level, msg string, fields ...Field) {
    contextFields := ExtractFieldsFromContext(ctx)
    allFields := append(contextFields, fields...)
    l.Log(level, msg, allFields...)
}
Source Reference: context.go:185-221

Usage Examples

Manual Field Extraction

func processRequest(ctx context.Context) {
    traceID := go_logs.GetTraceID(ctx)
    userID := go_logs.GetUserID(ctx)
    
    if traceID != "" && userID != "" {
        fmt.Printf("Processing trace %s for user %s\n", traceID, userID)
    }
}

Conditional Logging Based on Context

func debugHandler(ctx context.Context, msg string) {
    // Only log debug info if trace ID is present
    if go_logs.GetTraceID(ctx) != "" {
        logger.Debug(msg, go_logs.ExtractFieldsFromContext(ctx)...)
    }
}

Custom Middleware

func LoggingMiddleware(next http.Handler) http.Handler {
    return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
        ctx := r.Context()
        
        // Extract trace ID from header
        traceID := r.Header.Get("X-Trace-ID")
        if traceID != "" {
            ctx = go_logs.WithTraceID(ctx, traceID)
        }
        
        // Later in the request...
        if id := go_logs.GetTraceID(ctx); id != "" {
            w.Header().Set("X-Trace-ID", id)
        }
        
        next.ServeHTTP(w, r.WithContext(ctx))
    })
}

Implementation Details

Type Safety

All getter functions perform type assertion to ensure the value is a string:
// Source: context.go:122-128
func GetTraceID(ctx context.Context) string {
    if v := ctx.Value(traceIDKey); v != nil {
        if traceID, ok := v.(string); ok {
            return traceID
        }
    }
    return ""
}
This prevents panics if someone accidentally stores a non-string value using the same context key.

Zero-Value Safety

All functions return empty strings (not nil) when metadata is not present, making them safe to use without nil checks:
// Safe - no nil check needed
traceID := go_logs.GetTraceID(ctx)
logger.Info("Message", go_logs.String("trace", traceID))
See Context Propagation for functions that add values to contexts.

Build docs developers (and LLMs) love