-
Notifications
You must be signed in to change notification settings - Fork 16
/
logger.go
219 lines (196 loc) · 5.36 KB
/
logger.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
//
// DISCLAIMER
//
// Copyright 2017 ArangoDB GmbH, Cologne, Germany
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
//
// Copyright holder is ArangoDB GmbH, Cologne, Germany
//
// Author Ewout Prangsma
//
package logging
import (
"fmt"
"io"
"io/ioutil"
"os"
"strings"
"sync"
"time"
"github.com/rs/zerolog"
)
type TimeFormat int
const (
TimeFormatLocal TimeFormat = 0
TimeFormatUTC TimeFormat = 1
)
var (
// The defaultLevels list is used during development to increase the
// default level for components that we care a little less about.
defaultLevels = map[string]string{
"cluster.update": "info",
//"master.sync.status": "info",
"master.workers": "info",
//"mq.kafka": "info",
//"mq.kafka.driver": "info",
"mq.nats": "info",
"mq.direct.remote": "info",
"server.requests": "info",
//"task.receive-inventory": "info",
"worker.directMQ": "debug",
"worker.registration": "info",
}
)
// Service exposes the interfaces for a logger service
// that supports different loggers with different levels.
type Service interface {
// MustGetLogger creates a logger with given name.
MustGetLogger(name string) zerolog.Logger
// MustSetLevel sets the log level for the component with given name to given level.
MustSetLevel(name, level string)
// RotateLogFiles re-opens log file writer.
RotateLogFiles()
}
// loggingService implements Service
type loggingService struct {
mutex sync.Mutex
rootLog zerolog.Logger
defaultLevel zerolog.Level
levels map[string]zerolog.Level
rotate func()
}
type LoggerOutputOptions struct {
Color bool // Produce colored logs
TimeFormat TimeFormat // Instructs how to print time in logs
Stderr bool // Write logs to stderr
LogFile string // Path of file to write to
}
func configureLogger(lg zerolog.ConsoleWriter) zerolog.ConsoleWriter {
lg.TimeFormat = time.RFC3339
lg.FormatLevel = func(i interface{}) string {
return fmt.Sprintf("|%s|", strings.ToUpper(fmt.Sprintf("%s", i)))
}
return lg
}
// NewRootLogger creates a new zerolog logger with default settings.
func NewRootLogger(options LoggerOutputOptions) (zerolog.Logger, func()) {
var writers []io.Writer
var errors []error
var rotate func()
if options.TimeFormat == TimeFormatUTC {
zerolog.TimestampFunc = func() time.Time {
return time.Now().UTC()
}
}
if options.LogFile != "" {
fileWriter, err := newRotatingWriter(options.LogFile)
if err != nil {
errors = append(errors, err)
options.Stderr = true
} else {
rotate = func() { fileWriter.Rotate() }
writer := configureLogger(zerolog.ConsoleWriter{
Out: fileWriter,
NoColor: true,
})
writers = append(writers, writer)
}
}
if options.Stderr {
writer := configureLogger(zerolog.ConsoleWriter{
Out: os.Stderr,
NoColor: !options.Color,
})
writers = append(writers, writer)
}
var writer io.Writer
switch len(writers) {
case 0:
writer = ioutil.Discard
case 1:
writer = writers[0]
default:
writer = io.MultiWriter(writers...)
}
l := zerolog.New(writer).With().Timestamp().Logger()
if len(errors) > 0 {
for _, err := range errors {
l.Error().Msg(err.Error())
}
l.Fatal().Msg("Failed to initialize logging")
}
return l, rotate
}
// NewService creates a new Service.
func NewService(defaultLevel string, options LoggerOutputOptions) (Service, error) {
l, err := stringToLevel(defaultLevel)
if err != nil {
return nil, maskAny(err)
}
rootLog, rotate := NewRootLogger(options)
s := &loggingService{
rootLog: rootLog,
defaultLevel: l,
levels: make(map[string]zerolog.Level),
rotate: rotate,
}
for k, v := range defaultLevels {
s.MustSetLevel(k, v)
}
return s, nil
}
// MustGetLogger creates a logger with given name
func (s *loggingService) MustGetLogger(name string) zerolog.Logger {
s.mutex.Lock()
defer s.mutex.Unlock()
level, found := s.levels[name]
if !found {
level = s.defaultLevel
}
return s.rootLog.With().Str("component", name).Logger().Level(level)
}
// MustSetLevel sets the log level for the component with given name to given level.
func (s *loggingService) MustSetLevel(name, level string) {
l, err := stringToLevel(level)
if err != nil {
panic(err)
}
s.mutex.Lock()
defer s.mutex.Unlock()
s.levels[name] = l
}
// RotateLogFiles re-opens log file writer.
func (s *loggingService) RotateLogFiles() {
if s.rotate != nil {
s.rotate()
}
}
// stringToLevel converts a level string to a zerolog level
func stringToLevel(l string) (zerolog.Level, error) {
switch strings.ToLower(l) {
case "debug":
return zerolog.DebugLevel, nil
case "info":
return zerolog.InfoLevel, nil
case "warn", "warning":
return zerolog.WarnLevel, nil
case "error":
return zerolog.ErrorLevel, nil
case "fatal":
return zerolog.FatalLevel, nil
case "panic":
return zerolog.PanicLevel, nil
}
return zerolog.InfoLevel, fmt.Errorf("Unknown log level '%s'", l)
}