git.sr.ht/~pingoo/stdx@v0.0.0-20240218134121-094174641f6e/log/slogx/ctx.go (about)

     1  package slogx
     2  
     3  import (
     4  	"context"
     5  	"log/slog"
     6  	"os"
     7  )
     8  
     9  type contextKey struct{}
    10  
    11  var ctxKey = contextKey{}
    12  
    13  // ToCtx returns a copy of ctx with logger associated.
    14  func ToCtx(ctx context.Context, logger *slog.Logger) context.Context {
    15  	// if existingLogger, ok := ctx.Value(ctxKey{}).(*slog.Logger); ok {
    16  	// 	if existingLogger == logger {
    17  	// 		// Do not store same logger.
    18  	// 		return ctx
    19  	// 	}
    20  	// }
    21  	return context.WithValue(ctx, ctxKey, logger)
    22  }
    23  
    24  // FromCtx returns the Logger associated with the ctx. If no logger
    25  // is associated, a New() logger is returned with a addedfield "slogx.FromCtx": "error".
    26  //
    27  // For example, to add a field to an existing logger in the context, use this
    28  // notation:
    29  //
    30  //	ctx := r.Context()
    31  //	logger := slogx.FromCtx(ctx)
    32  //	logger = logger.With(...)
    33  func FromCtx(ctx context.Context) *slog.Logger {
    34  	if existingLogger, ok := ctx.Value(ctxKey).(*slog.Logger); ok {
    35  		return existingLogger
    36  	}
    37  	logger := slog.New(slog.NewJSONHandler(os.Stdout, nil)).With(slog.String("slogx.FromCtx", "error"))
    38  	return logger
    39  }