Last active
December 16, 2021 13:59
-
-
Save r3code/06e4427637d8017864d0dc23623933d6 to your computer and use it in GitHub Desktop.
log-trace-connector demo
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
package main | |
// live https://goplay.space/#qUqusVmj8oV | |
import ( | |
"context" | |
"fmt" | |
) | |
func NewService(l *Logger) *Service { | |
return &Service{ | |
logger: func(ctx context.Context) *Logger { | |
// create a new context logger from the existing | |
ll := &Logger{l.fields} | |
return LogWithTracing(ctx, ll) | |
}, | |
} | |
} | |
func (s *Service) ServiceMethod(ctx context.Context, source string) { | |
s.logger(ctx).Log(source) | |
} | |
type Logger struct { | |
fields string | |
} | |
func (l *Logger) Log(s string) { | |
fmt.Println("LOG::fields->[" + l.fields + "] :: s=" + s) | |
} | |
func (l *Logger) AddField(f string, val string) { | |
l.fields = l.fields + fmt.Sprintf(" %s=%s", f, val) | |
} | |
type Service struct { | |
logger func(ctx context.Context) *Logger | |
} | |
func LogWithTracing(ctx context.Context, l *Logger) *Logger { | |
l.AddField("LogWithTracing", "worked") | |
if v := ctx.Value(ctxMarkerKey); v != nil { | |
l.AddField("ctx_value", v.(string)) | |
} | |
return l | |
} | |
type ctxMarker struct{} | |
var ( | |
ctxMarkerKey = &ctxMarker{} | |
) | |
func main() { | |
fmt.Println("Start.") | |
l := &Logger{} | |
l.Log("simple log") | |
s := NewService(l) | |
c1 := context.Background() | |
s.ServiceMethod(c1, "Call to ServiceMethod_1") | |
// Immitate tracer injected tracing context into a request context | |
c2 := context.WithValue(c1, ctxMarkerKey, "tracing_context") | |
s.ServiceMethod(c2, "Call to ServiceMethod_2") | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment