Skip to content

Commit e606cda

Browse files
committed
Context-based tracing
1 parent daaad09 commit e606cda

File tree

370 files changed

+218637
-6513
lines changed

Some content is hidden

Large Commits have some content hidden by default. Use the searchbox below for content that may be hidden.

370 files changed

+218637
-6513
lines changed

context/context.go

Lines changed: 90 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,90 @@
1+
package context
2+
3+
import (
4+
"fmt"
5+
"github.com/oklog/ulid"
6+
"github.com/sirupsen/logrus"
7+
"io"
8+
"math/rand"
9+
"time"
10+
)
11+
12+
const (
13+
Error = 0
14+
Warning = 1
15+
Info = 2
16+
Debug = 3
17+
Trace = 4
18+
)
19+
20+
var allLevels = []logrus.Level{
21+
logrus.ErrorLevel,
22+
logrus.WarnLevel,
23+
logrus.InfoLevel,
24+
logrus.DebugLevel,
25+
logrus.TraceLevel,
26+
}
27+
28+
type Fields map[string]interface{}
29+
30+
type Context struct {
31+
Trace string
32+
index uint64 // given Context is intended to be used in single-threaded fashion so we use uint instead of ULID
33+
34+
level logrus.Level
35+
fields map[string]interface{}
36+
}
37+
38+
func Init(level int, output io.Writer) {
39+
logrus.SetFormatter(&logrus.JSONFormatter{})
40+
logrus.SetOutput(output)
41+
logrus.SetLevel(convertLevel(level))
42+
}
43+
44+
func New() (ctx *Context) {
45+
ctx = new(Context)
46+
ctx.Trace = newULID()
47+
ctx.fields = make(map[string]interface{})
48+
return
49+
}
50+
51+
func (ctx *Context) Derived() (derived *Context) {
52+
ctx.index += 1
53+
derived = New()
54+
derived.Trace = fmt.Sprintf("%s.%d", ctx.Trace, ctx.index)
55+
return
56+
}
57+
58+
func (ctx *Context) Level(level int) *Context {
59+
ctx.level = convertLevel(level)
60+
return ctx
61+
}
62+
63+
func (ctx *Context) Field(name string, value interface{}) *Context {
64+
ctx.fields[name] = value
65+
return ctx
66+
}
67+
68+
func (ctx *Context) Message(message string) {
69+
ctx.fields["::trace"] = ctx.Trace
70+
71+
logrus.WithFields(ctx.fields).Log(ctx.level, message)
72+
}
73+
74+
func convertLevel(level int) logrus.Level {
75+
if level < 0 || level >= len(allLevels) {
76+
panic(
77+
fmt.Sprintf(
78+
"Wrong log level '%d' - only '0' (least verbose) to '%d' (most verbose) supported",
79+
level, len(allLevels)-1))
80+
}
81+
82+
return allLevels[level]
83+
}
84+
85+
func newULID() string {
86+
t := time.Now()
87+
entropy := ulid.Monotonic(rand.New(rand.NewSource(t.UnixNano())), 0)
88+
value := ulid.MustNew(ulid.Timestamp(t), entropy)
89+
return value.String()
90+
}

0 commit comments

Comments
 (0)