// Copyright (C) 2022 The OKit Authors // // Permission is hereby granted, free of charge, to any person obtaining a copy // of this software and associated documentation files (the "Software"), to deal // in the Software without restriction, including without limitation the rights // to use, copy, modify, merge, publish, distribute, sublicense, and/or sell // copies of the Software, and to permit persons to whom the Software is // furnished to do so, subject to the following conditions: // // The above copyright notice and this permission notice shall be included in all // copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, // EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF // MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. // IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, // DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR // OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE // OR OTHER DEALINGS IN THE SOFTWARE. package okit import ( "context" "crypto/rand" "encoding/base32" "io" "runtime" "time" "go.pitz.tech/okit/pb" ) var encoding = base32.StdEncoding.WithPadding(base32.NoPadding) // NewClient produces a new default client implementation for emitting metrics. func NewClient() Client { return Client{ now: time.Now, uuid: func() string { buf := make([]byte, 16) n, err := io.ReadFull(rand.Reader, buf) if err != nil { panic(err) } return encoding.EncodeToString(buf[:n]) }, callerSkip: 2, } } // Client provides a default implementation. type Client struct { now func() time.Time uuid func() string tags []Tag callerSkip int } // WithNow configures the function that's used to obtain the current timestamp. func (o Client) WithNow(now func() time.Time) Client { o.now = now return o } // WithUUID returns a new uuid that uniquely identifies traces, spans, and tags. func (o Client) WithUUID(uuid func() string) Client { o.uuid = uuid return o } // WithCallerSkip is used to configure the number of frames to skip when determining the caller. Callers are // predominantly used when performing traces. func (o Client) WithCallerSkip(callerSkip int) Client { o.callerSkip = callerSkip return o } // With appends tags to the current client that will automatically be added to all events, metrics, logs, and traces. func (o Client) With(tags ...Tag) Client { o.tags = append(o.tags, tags...) return o } // Emit allows for the emission of an event which has now value and only associated tags. func (o Client) Emit(event string, tags ...Tag) { o.With(tags...).emit(&pb.Entry{ Kind: pb.Kind_Event, Scope: event, }) } // Observe reports a metric and it's associated value. func (o Client) Observe(metric string, value float64, tags ...Tag) { o.With(tags...).emit(&pb.Entry{ Value: &pb.Entry_Double{Double: value}, Kind: pb.Kind_Metric, Scope: metric, }) } // Trace allows a method to be traced, and it's execution time recorded and reported for viewing. func (o Client) Trace(ctx context.Context, tags ...Tag) (context.Context, DoneFunc) { name, _ := caller(o.callerSkip) start := o.now() span := Span{ TraceID: o.uuid(), ID: o.uuid(), } v := ctx.Value(SpanKey) if v != nil { parent, hasParent := v.(Span) if hasParent { span.TraceID = parent.TraceID span.ParentID = parent.ID } } //goland:noinspection GoAssignmentToReceiver o = o.With( append( []Tag{ String("traceId", span.TraceID), String("traceSpanId", span.ID), String("traceParentId", span.ParentID), }, tags..., )..., ) // bookend o.With(String("bookend", "start")).emit(&pb.Entry{ Kind: pb.Kind_Log, Scope: name, Value: &pb.Entry_String_{String_: "trace"}, }) return context.WithValue(ctx, SpanKey, span), func() { duration := o.now().Sub(start) // bookend o.With(String("bookend", "end")).emit(&pb.Entry{ Kind: pb.Kind_Log, Scope: name, Value: &pb.Entry_String_{String_: "trace"}, }) // trace o.emit( &pb.Entry{ Kind: pb.Kind_Trace, Scope: name, Value: &pb.Entry_Duration{Duration: pb.DurationPB(duration)}, }, ) } } // Debug produces a debug log event. func (o Client) Debug(msg string, tags ...Tag) { o.With(tags...).emit(&pb.Entry{ Kind: pb.Kind_Log, Scope: msg, Value: &pb.Entry_String_{String_: "debug"}, }) } // Info produces an information log event. func (o Client) Info(msg string, tags ...Tag) { o.With(tags...).emit(&pb.Entry{ Kind: pb.Kind_Log, Scope: msg, Value: &pb.Entry_String_{String_: "info"}, }) } // Warn produces a warning that is surfaced to operators. func (o Client) Warn(msg string, tags ...Tag) { o.With(tags...).emit(&pb.Entry{ Kind: pb.Kind_Log, Scope: msg, Value: &pb.Entry_String_{String_: "warn"}, }) } // Error produces a message that communicates an error has occurred. func (o Client) Error(msg string, tags ...Tag) { o.With(tags...).emit(&pb.Entry{ Kind: pb.Kind_Log, Scope: msg, Value: &pb.Entry_String_{String_: "error"}, }) } func (o Client) emit(entries ...*pb.Entry) { now := pb.TimestampPB(o.now()) tags := make([]*pb.Tag, 0, len(o.tags)) for _, tag := range o.tags { tags = append(tags, tag.AsTagPB()) } for _, entry := range entries { entry.Timestamp = now entry.Tags = tags _ = DefaultFormat.Marshal(sink, entry) } _ = sink.Flush() } // caller attempts to get method caller information. This information is used for tracing information across an // applications source code. func caller(skip int) (name string, line int) { pctr, _, line, ok := runtime.Caller(skip) if !ok { return "", 0 } return runtime.FuncForPC(pctr).Name(), line }