1 Star 0 Fork 0

bughou / go

加入 Gitee
与超过 1200万 开发者一起发现、参与优秀开源项目,私有仓库也完全免费 :)
免费加入
克隆/下载
tracer.go 2.48 KB
一键复制 编辑 原始数据 按行查看 历史
bughou 提交于 2022-03-20 18:50 . save
package tracer
import (
"context"
"fmt"
"sync"
"time"
)
type Tracer struct {
sync.Mutex
Name string `json:"name,omitempty"`
At time.Time `json:"at"`
Duration float64 `json:"duration"` // milliseconds
Children []*Tracer `json:"children,omitempty"`
Tags map[string]interface{} `json:"tags,omitempty"`
Logs []string `json:"logs,omitempty"`
}
// Start start a new tracer on the given context
func Start(ctx context.Context, name string) context.Context {
if ctx == nil {
return nil
}
tracer := &Tracer{Name: name, At: time.Now()}
if parent := Get(ctx); parent != nil {
parent.Children = append(parent.Children, tracer)
}
return context.WithValue(ctx, key, tracer)
}
// Start start a child tracer on the given context
func StartChild(ctx context.Context, name string) context.Context {
parent := Get(ctx)
if parent == nil {
return ctx
}
tracer := &Tracer{Name: name, At: time.Now()}
parent.Children = append(parent.Children, tracer)
return context.WithValue(ctx, key, tracer)
}
// Finish finish the tracer on the given context
func Finish(ctx context.Context) {
if tracer := Get(ctx); tracer != nil {
tracer.Duration = float64(time.Since(tracer.At)) / float64(time.Millisecond)
}
}
// Tag add a tag to a tracer context
func Tag(ctx context.Context, k string, v interface{}) {
if tracer := Get(ctx); tracer != nil {
if tracer.Tags == nil {
tracer.Tags = make(map[string]interface{})
}
tracer.Lock()
tracer.Tags[k] = v
tracer.Unlock()
}
}
// DebugTag add a tag to a tracer context if debug is enabled
func DebugTag(ctx context.Context, k string, v interface{}) {
if IsDebug(ctx) {
Tag(ctx, k, v)
}
}
// Log add a log to a tracer context using Sprint
func Log(ctx context.Context, args ...interface{}) {
if tracer := Get(ctx); tracer != nil {
tracer.Logs = append(tracer.Logs, fmt.Sprint(args...))
}
}
// Logf add a log to a tracer context using Sprintf
func Logf(ctx context.Context, format string, args ...interface{}) {
if tracer := Get(ctx); tracer != nil {
tracer.Logs = append(tracer.Logs, fmt.Sprintf(format, args...))
}
}
// DebugLog add a log to a tracer context if debug is enabled
func DebugLog(ctx context.Context, args ...interface{}) {
if IsDebug(ctx) {
Log(ctx, args...)
}
}
// DebugLogf add a log to a tracer context if debug is enabled
func DebugLogf(ctx context.Context, format string, args ...interface{}) {
if IsDebug(ctx) {
Logf(ctx, format, args...)
}
}
马建仓 AI 助手
尝试更多
代码解读
代码找茬
代码优化
Go
1
https://gitee.com/bughou/go.git
git@gitee.com:bughou/go.git
bughou
go
go
d31700df43a9

搜索帮助

344bd9b3 5694891 D2dac590 5694891