go.charczuk.com@v0.0.0-20240327042549-bc490516bd1a/sdk/logutil/context.go (about) 1 /* 2 3 Copyright (c) 2023 - Present. Will Charczuk. All rights reserved. 4 Use of this source code is governed by a MIT license that can be found in the LICENSE file at the root of the repository. 5 6 */ 7 8 package logutil 9 10 import ( 11 "context" 12 "log" 13 ) 14 15 type loggerKey struct{} 16 17 // WithLoger adds a logger to a given context. 18 func WithLogger(ctx context.Context, l *log.Logger) context.Context { 19 return context.WithValue(ctx, loggerKey{}, l) 20 } 21 22 // GetLogger returns the logger from a given context. 23 // 24 // If no logger is present on the context a shardd discard logger is returned 25 // which will ignore logging calls (but is still a valid reference!) 26 func GetLogger(ctx context.Context) *log.Logger { 27 if value := ctx.Value(loggerKey{}); value != nil { 28 if typed, ok := value.(*log.Logger); ok { 29 return typed 30 } 31 } 32 return Discard() 33 }