forked from bigpigeon/beats
-
Notifications
You must be signed in to change notification settings - Fork 0
/
core.go
200 lines (172 loc) · 4.92 KB
/
core.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
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
package logp
import (
"flag"
"io/ioutil"
golog "log"
"os"
"path/filepath"
"sync/atomic"
"unsafe"
"github.com/pkg/errors"
"go.uber.org/zap"
"go.uber.org/zap/zapcore"
"go.uber.org/zap/zaptest/observer"
"github.com/elastic/beats/libbeat/common/file"
"github.com/elastic/beats/libbeat/paths"
)
var (
_log unsafe.Pointer // Pointer to a coreLogger. Access via atomic.LoadPointer.
)
func init() {
storeLogger(&coreLogger{
selectors: map[string]struct{}{},
rootLogger: zap.NewNop(),
globalLogger: zap.NewNop(),
})
}
type coreLogger struct {
selectors map[string]struct{}
rootLogger *zap.Logger
globalLogger *zap.Logger
observedLogs *observer.ObservedLogs
}
// Configure configures the logp package.
func Configure(cfg Config) error {
var (
sink zapcore.Core
observedLogs *observer.ObservedLogs
err error
)
// Build a single output (stderr has priority if more than one are enabled).
switch {
case cfg.toObserver:
sink, observedLogs = observer.New(cfg.Level.zapLevel())
case cfg.toIODiscard:
sink, err = makeDiscardOutput(cfg)
case cfg.ToStderr:
sink, err = makeStderrOutput(cfg)
case cfg.ToSyslog:
sink, err = makeSyslogOutput(cfg)
case cfg.ToEventLog:
sink, err = makeEventLogOutput(cfg)
case cfg.ToFiles:
fallthrough
default:
sink, err = makeFileOutput(cfg)
}
if err != nil {
return errors.Wrap(err, "failed to build log output")
}
// Enabled selectors when debug is enabled.
selectors := make(map[string]struct{}, len(cfg.Selectors))
if cfg.Level.Enabled(DebugLevel) && len(cfg.Selectors) > 0 {
for _, sel := range cfg.Selectors {
selectors[sel] = struct{}{}
}
// Default to all enabled if no selectors are specified.
if len(selectors) == 0 {
selectors["*"] = struct{}{}
}
if _, enabled := selectors["stdlog"]; !enabled {
// Disable standard logging by default (this is sometimes used by
// libraries and we don't want their spam).
golog.SetOutput(ioutil.Discard)
}
sink = selectiveWrapper(sink, selectors)
}
root := zap.New(sink, makeOptions(cfg)...)
storeLogger(&coreLogger{
selectors: selectors,
rootLogger: root,
globalLogger: root.WithOptions(zap.AddCallerSkip(1)),
observedLogs: observedLogs,
})
return nil
}
// DevelopmentSetup configures the logger in development mode at debug level.
// By default the output goes to stderr.
func DevelopmentSetup(options ...Option) error {
cfg := Config{
Level: DebugLevel,
ToStderr: true,
development: true,
addCaller: true,
}
for _, apply := range options {
apply(&cfg)
}
return Configure(cfg)
}
// TestingSetup configures logging by calling DevelopmentSetup if and only if
// verbose testing is enabled (as in 'go test -v').
func TestingSetup(options ...Option) error {
// Use the flag to avoid a dependency on the testing package.
f := flag.Lookup("test.v")
if f != nil && f.Value.String() == "true" {
return DevelopmentSetup(options...)
}
return nil
}
// ObserverLogs provides the list of logs generated during the observation
// process.
func ObserverLogs() *observer.ObservedLogs {
return loadLogger().observedLogs
}
// Sync flushes any buffered log entries. Applications should take care to call
// Sync before exiting.
func Sync() error {
return loadLogger().rootLogger.Sync()
}
func makeOptions(cfg Config) []zap.Option {
var options []zap.Option
if cfg.addCaller {
options = append(options, zap.AddCaller())
}
if cfg.development {
options = append(options, zap.Development())
}
return options
}
func makeStderrOutput(cfg Config) (zapcore.Core, error) {
stderr := zapcore.Lock(os.Stderr)
return zapcore.NewCore(buildEncoder(cfg), stderr, cfg.Level.zapLevel()), nil
}
func makeDiscardOutput(cfg Config) (zapcore.Core, error) {
discard := zapcore.AddSync(ioutil.Discard)
return zapcore.NewCore(buildEncoder(cfg), discard, cfg.Level.zapLevel()), nil
}
func makeSyslogOutput(cfg Config) (zapcore.Core, error) {
return newSyslog(buildEncoder(cfg), cfg.Level.zapLevel())
}
func makeEventLogOutput(cfg Config) (zapcore.Core, error) {
return newEventLog(cfg.Beat, buildEncoder(cfg), cfg.Level.zapLevel())
}
func makeFileOutput(cfg Config) (zapcore.Core, error) {
name := cfg.Beat
if cfg.Files.Name != "" {
name = cfg.Files.Name
}
filename := paths.Resolve(paths.Logs, filepath.Join(cfg.Files.Path, name))
rotator, err := file.NewFileRotator(filename,
file.MaxSizeBytes(cfg.Files.MaxSize),
file.MaxBackups(cfg.Files.MaxBackups),
file.Permissions(os.FileMode(cfg.Files.Permissions)),
)
if err != nil {
return nil, errors.Wrap(err, "failed to create file rotator")
}
return zapcore.NewCore(buildEncoder(cfg), rotator, cfg.Level.zapLevel()), nil
}
func globalLogger() *zap.Logger {
return loadLogger().globalLogger
}
func loadLogger() *coreLogger {
p := atomic.LoadPointer(&_log)
return (*coreLogger)(p)
}
func storeLogger(l *coreLogger) {
if old := loadLogger(); old != nil {
old.rootLogger.Sync()
}
atomic.StorePointer(&_log, unsafe.Pointer(l))
}