-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathfields.go
61 lines (50 loc) · 1.54 KB
/
fields.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
package logutil
import (
"path"
"github.com/cockroachdb/errors"
"go.stevenxie.me/gopkg/name"
"github.com/sirupsen/logrus"
"go.stevenxie.me/gopkg/zero"
)
const (
// SourceKey is the field key used to store the type name of the logging
// source.
SourceKey = "source"
// MethodKey is the field key used to store the method name where the logger
// is being called.
MethodKey = "method"
// ComponentKey is the field key used to store the logging object's component
// path.
ComponentKey = "component"
)
// WithSource adds the type name of v to a logrus.Entry.
func WithSource(e *logrus.Entry, v zero.Interface) *logrus.Entry {
name := name.OfType(v)
return e.WithField(SourceKey, name)
}
// WithMethod adds the name of the method v to the logrus.Entry.
func WithMethod(e *logrus.Entry, v zero.Interface) *logrus.Entry {
return e.WithField(MethodKey, name.OfMethod(v))
}
// WithComponent appends the component to the component path field of the
// logrus.Entry.
func WithComponent(e *logrus.Entry, component string) *logrus.Entry {
if _, ok := e.Data[ComponentKey]; !ok {
return e.WithField(ComponentKey, component)
}
// Extract existing component elems, if any.
var elems []string
if component, ok := e.Data[ComponentKey]; ok {
s, ok := component.(string)
if !ok {
panic(errors.Newf(
"logutil: entry contains component field of unknown type '%T'",
component,
))
}
elems = append(elems, s)
}
// Append latest component name to
elems = append(elems, component)
return e.WithField(ComponentKey, path.Join(elems...))
}