forked from elastic/beats
-
Notifications
You must be signed in to change notification settings - Fork 0
/
logp.go
247 lines (214 loc) · 5.72 KB
/
logp.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
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
package logp
import (
"expvar"
"flag"
"fmt"
"io/ioutil"
"log"
"strconv"
"strings"
"time"
"github.com/elastic/beats/libbeat/paths"
)
var (
// cmd line flags
verbose *bool
toStderr *bool
debugSelectorsStr *string
// Beat start time
startTime time.Time
)
func init() {
startTime = time.Now()
}
type Logging struct {
Selectors []string
Files *FileRotator
ToSyslog *bool `config:"to_syslog"`
ToFiles *bool `config:"to_files"`
Level string
Metrics LoggingMetricsConfig `config:"metrics"`
}
type LoggingMetricsConfig struct {
Enabled *bool `config:"enabled"`
Period *time.Duration `config:"period" validate:"nonzero,min=0s"`
}
var (
defaultMetricsPeriod = 30 * time.Second
)
func init() {
// Adds logging specific flags: -v, -e and -d.
verbose = flag.Bool("v", false, "Log at INFO level")
toStderr = flag.Bool("e", false, "Log to stderr and disable syslog/file output")
debugSelectorsStr = flag.String("d", "", "Enable certain debug selectors")
}
// Init combines the configuration from config with the command line
// flags to initialize the Logging systems. After calling this function,
// standard output is always enabled. You can make it respect the command
// line flag with a later SetStderr call.
func Init(name string, config *Logging) error {
logLevel, err := getLogLevel(config)
if err != nil {
return err
}
if *verbose {
if LOG_INFO > logLevel {
logLevel = LOG_INFO
}
}
debugSelectors := config.Selectors
if logLevel == LOG_DEBUG {
if len(debugSelectors) == 0 {
debugSelectors = []string{"*"}
}
}
if len(*debugSelectorsStr) > 0 {
debugSelectors = strings.Split(*debugSelectorsStr, ",")
logLevel = LOG_DEBUG
}
// default log location is in the logs path
defaultFilePath := paths.Resolve(paths.Logs, "")
var toSyslog, toFiles bool
if config.ToSyslog != nil {
toSyslog = *config.ToSyslog
} else {
toSyslog = false
}
if config.ToFiles != nil {
toFiles = *config.ToFiles
} else {
toFiles = true
}
// toStderr disables logging to syslog/files
if *toStderr {
toSyslog = false
toFiles = false
}
LogInit(Priority(logLevel), "", toSyslog, true, debugSelectors)
if len(debugSelectors) > 0 {
config.Selectors = debugSelectors
}
if toFiles {
if config.Files == nil {
config.Files = &FileRotator{
Path: defaultFilePath,
Name: name,
}
} else {
if config.Files.Path == "" {
config.Files.Path = defaultFilePath
}
if config.Files.Name == "" {
config.Files.Name = name
}
}
err := SetToFile(true, config.Files)
if err != nil {
return err
}
}
if IsDebug("stdlog") {
// disable standard logging by default (this is sometimes
// used by libraries and we don't want their logs to spam ours)
log.SetOutput(ioutil.Discard)
}
go logExpvars(&config.Metrics)
return nil
}
func SetStderr() {
if !*toStderr {
SetToStderr(false, "")
Debug("log", "Disable stderr logging")
}
}
func getLogLevel(config *Logging) (Priority, error) {
if config == nil || config.Level == "" {
return LOG_INFO, nil
}
levels := map[string]Priority{
"critical": LOG_CRIT,
"error": LOG_ERR,
"warning": LOG_WARNING,
"info": LOG_INFO,
"debug": LOG_DEBUG,
}
level, ok := levels[strings.ToLower(config.Level)]
if !ok {
return 0, fmt.Errorf("unknown log level: %v", config.Level)
}
return level, nil
}
// snapshotMap recursively walks expvar Maps and records their integer expvars
// in a separate flat map.
func snapshotMap(varsMap map[string]int64, path string, mp *expvar.Map) {
mp.Do(func(kv expvar.KeyValue) {
switch kv.Value.(type) {
case *expvar.Int:
varsMap[path+"."+kv.Key], _ = strconv.ParseInt(kv.Value.String(), 10, 64)
case *expvar.Map:
snapshotMap(varsMap, path+"."+kv.Key, kv.Value.(*expvar.Map))
}
})
}
// snapshotExpvars iterates through all the defined expvars, and for the vars
// that are integers it snapshots the name and value in a separate (flat) map.
func snapshotExpvars(varsMap map[string]int64) {
expvar.Do(func(kv expvar.KeyValue) {
switch kv.Value.(type) {
case *expvar.Int:
varsMap[kv.Key], _ = strconv.ParseInt(kv.Value.String(), 10, 64)
case *expvar.Map:
snapshotMap(varsMap, kv.Key, kv.Value.(*expvar.Map))
}
})
}
// buildMetricsOutput makes the delta between vals and prevVals and builds
// a printable string with the non-zero deltas.
func buildMetricsOutput(prevVals map[string]int64, vals map[string]int64) string {
metrics := ""
for k, v := range vals {
delta := v - prevVals[k]
if delta != 0 {
metrics = fmt.Sprintf("%s %s=%d", metrics, k, delta)
}
}
return metrics
}
// logExpvars logs at Info level the integer expvars that have changed in the
// last interval. For each expvar, the delta from the beginning of the interval
// is logged.
func logExpvars(metricsCfg *LoggingMetricsConfig) {
if metricsCfg.Enabled != nil && *metricsCfg.Enabled == false {
Info("Metrics logging disabled")
return
}
if metricsCfg.Period == nil {
metricsCfg.Period = &defaultMetricsPeriod
}
Info("Metrics logging every %s", metricsCfg.Period)
ticker := time.NewTicker(*metricsCfg.Period)
prevVals := map[string]int64{}
for {
<-ticker.C
vals := map[string]int64{}
snapshotExpvars(vals)
metrics := buildMetricsOutput(prevVals, vals)
prevVals = vals
if len(metrics) > 0 {
Info("Non-zero metrics in the last %s:%s", metricsCfg.Period, metrics)
} else {
Info("No non-zero metrics in the last %s", metricsCfg.Period)
}
}
}
func LogTotalExpvars(cfg *Logging) {
if cfg.Metrics.Enabled != nil && *cfg.Metrics.Enabled == false {
return
}
vals := map[string]int64{}
prevVals := map[string]int64{}
snapshotExpvars(vals)
metrics := buildMetricsOutput(prevVals, vals)
Info("Total non-zero values: %s", metrics)
Info("Uptime: %s", time.Now().Sub(startTime))
}