-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathcannon.go
More file actions
63 lines (56 loc) · 2.08 KB
/
Copy pathcannon.go
File metadata and controls
63 lines (56 loc) · 2.08 KB
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
package cannon
import (
"errors"
"time"
"github.com/BTBurke/cannon/internal"
"go.uber.org/zap"
"go.uber.org/zap/zapcore"
)
// Core creates a new zapcore.Core that exends zap's logging core to enable cannonical logging when the Emit method
// is called. This is a low level primitive that allows you to pass additional options to the zap logging contructor to
// get exactly the functionality you want. For a higher level log constructor, you can use `cannon.NewProduction()`,
// `cannon.NewDevelopment()`, or pass your own log factory to `RegisterFactory` and then call `cannon.NewLogger()`
func Core() zap.Option {
return zap.WrapCore(func(c zapcore.Core) zapcore.Core {
core := &internal.CannonicalLog{
EmptyCore: c,
WrappedCore: c,
}
return core
})
}
// Emit is called at the end of the request to emit the cannonical log line that contains all fields set throughout
// the lifetime of the call
func Emit(log *zap.Logger, fields ...zap.Field) error {
c, ok := log.Core().(*internal.CannonicalLog)
if !ok {
return errors.New("unknown logger type")
}
if len(c.Fields)+len(fields) == 0 {
return nil
}
if err := c.EmptyCore.Write(zapcore.Entry{
Time: time.Now(),
Message: "cannonical_log_line",
}, append(c.Fields, fields...)); err != nil {
return err
}
if err := c.EmptyCore.Sync(); err != nil {
return err
}
return nil
}
// NewDevelopment gives you a `zap.NewDevelopment` configuration with the ability to emit a cannonical logline
// at the end of the request
func NewDevelopment(options ...zap.Option) (*zap.Logger, error) {
return zap.NewDevelopment(append(options, Core())...)
}
// NewProduction gives you a `zap.NewProduction` configuration with the ability to emit a cannonical logline
// at the end of the request
func NewProduction(options ...zap.Option) (*zap.Logger, error) {
return zap.NewProduction(append(options, Core())...)
}
// NewExample gives you a zap.NewExample logger that is useful for examples by stripping timestamps from example output
func NewExample(options ...zap.Option) *zap.Logger {
return zap.NewExample(append(options, Core())...)
}