-
Notifications
You must be signed in to change notification settings - Fork 1
/
context.go
93 lines (80 loc) · 1.81 KB
/
context.go
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
package tracer
import (
"sync"
)
var DefaultContext Context = nil
func init() {
DefaultContext = NewContext(Debug)
}
type context struct {
sync.Locker
parent Context
writers []Writer
loggers map[string]Logger
children map[string]Context
minimumLevel uint8
}
type Context interface {
GetLogger(owner string) Logger
ChildContext(owner string) Context
RegisterWriter(writer Writer)
MinimumLevel(level uint8)
GetMinimumLevel() uint8
GetWriters() []Writer
OverwriteChildren()
}
func NewContext(minimumLevel uint8) Context {
return &context{
Locker: &sync.RWMutex{},
minimumLevel: minimumLevel,
writers: []Writer{},
loggers: map[string]Logger{},
children: map[string]Context{},
parent: DefaultContext,
}
}
func (c *context) ChildContext(owner string) Context {
child := NewContext(c.minimumLevel).(*context)
child.parent = c
c.children[owner] = child
return child
}
func (c *context) GetLogger(owner string) Logger {
c.Lock()
defer c.Unlock()
if _, ok := c.loggers[owner]; !ok {
c.loggers[owner] = &logger{
Locker: &sync.RWMutex{},
Context: c.ChildContext(owner),
owner: owner,
}
}
return c.loggers[owner]
}
func (c *context) RegisterWriter(writer Writer) {
c.Lock()
defer c.Unlock()
c.writers = append(c.writers, writer)
}
func (c *context) GetWriters() []Writer {
c.Lock()
defer c.Unlock()
var writers []Writer
if c.parent != nil {
writers = append(writers, c.parent.GetWriters()...)
}
writers = append(writers, c.writers...)
return writers
}
func (c *context) MinimumLevel(level uint8) {
c.minimumLevel = level
}
func (c *context) GetMinimumLevel() uint8 {
return c.minimumLevel
}
func (c *context) OverwriteChildren() {
for _, child := range c.children {
child.MinimumLevel(c.minimumLevel)
child.OverwriteChildren()
}
}