/
logger.go
207 lines (170 loc) · 4.23 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
/*
* Copyright 2023 Comcast Cable Communications Management, LLC
*
* 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.
*/
package logger
import (
"fmt"
"net/http"
"net/url"
"os"
"go.uber.org/zap"
"go.uber.org/zap/zapcore"
"gopkg.in/natefinch/lumberjack.v2"
)
var (
logger *zap.Logger
path string
atomicLevel zap.AtomicLevel
)
type lumberjackSink struct {
*lumberjack.Logger
}
type LoggerConfig struct {
LogLevel string
LogMethod string
LogFile LogFile
VectorEndpoint string
}
type LogFile struct {
Path string
MaxSize int
MaxBackups int
MaxAge int
}
func (lumberjackSink) Sync() error {
return nil
}
func Initialize(svc, hostname string, config LoggerConfig) {
atomicLevel = zap.NewAtomicLevel()
logger = zap.New(zapcore.NewCore(
zapcore.NewJSONEncoder(ProdEncoderConf()),
os.Stdout,
atomicLevel,
), zap.AddCaller(),
zap.Fields(
zap.Field{
Key: "app",
Type: zapcore.StringType,
String: svc,
},
zap.Field{
Key: "host",
Type: zapcore.StringType,
String: hostname,
},
))
if config.LogMethod == "file" {
ljWriteSyncer := zapcore.AddSync(&lumberjack.Logger{
Filename: config.LogFile.Path + "/" + svc + ".log",
MaxSize: config.LogFile.MaxSize, // megabytes
MaxBackups: config.LogFile.MaxBackups,
MaxAge: config.LogFile.MaxAge, // days
})
ljCore := zapcore.NewCore(
zapcore.NewJSONEncoder(ProdEncoderConf()),
ljWriteSyncer,
atomicLevel)
logger = logger.WithOptions(zap.WrapCore(func(zapcore.Core) zapcore.Core {
return zapcore.NewTee(logger.Core(), ljCore)
}))
}
if config.LogMethod == "vector" {
url, err := url.Parse(config.VectorEndpoint)
if err != nil {
panic(err)
}
err = zap.RegisterSink(url.Scheme, initVectorSink)
if err != nil {
panic(err)
}
vecWriteSyncer, _, err := zap.Open(url.String())
if err != nil {
panic(err)
}
ws := zapcore.Lock(vecWriteSyncer)
zcFields := make([]zapcore.Field, 0, 2)
zcFields = append(zcFields, zapcore.Field{
Key: "app",
Type: zapcore.StringType,
String: svc,
}, zapcore.Field{
Key: "host",
Type: zapcore.StringType,
String: hostname,
})
vectorCore := zapcore.NewCore(
zapcore.NewJSONEncoder(ProdEncoderConf()),
ws,
atomicLevel).With(zcFields)
logger = logger.WithOptions(zap.WrapCore(func(zapcore.Core) zapcore.Core {
return zapcore.NewTee(logger.Core(), vectorCore)
}))
}
atomicLevel.SetLevel(parseLevel(config.LogLevel))
zap.ReplaceGlobals(logger)
}
func Flush() {
if logger != nil {
logger.Sync()
}
}
func SetLevel(l string) {
atomicLevel.SetLevel(parseLevel(l))
}
func GetLevel() string {
return atomicLevel.Level().String()
}
func parseLevel(l string) zapcore.Level {
switch l {
case "debug":
return zap.DebugLevel
case "info":
return zap.InfoLevel
case "warn":
return zap.WarnLevel
case "error":
return zap.ErrorLevel
default:
return zap.InfoLevel
}
}
func ProdEncoderConf() zapcore.EncoderConfig {
encConf := zap.NewProductionEncoderConfig()
encConf.EncodeTime = zapcore.RFC3339TimeEncoder
return encConf
}
func Verbosity(w http.ResponseWriter, r *http.Request) {
type Results struct {
Level string `json:"verbosity"`
}
log := zap.L()
level := GetLevel()
log.Info("current logging level", zap.String("level", level))
w.WriteHeader(http.StatusOK)
fmt.Fprintf(w, "{\"verbosity\": \"%s\"}", level)
}
func SetVerbosity(w http.ResponseWriter, r *http.Request) {
log := zap.L()
query := r.URL.Query()
level := query.Get("v")
if level == "" {
http.Error(w, "'v' parameter is not set", http.StatusBadRequest)
return
}
SetLevel(level)
log.Info("updating logging level", zap.String("level", level))
w.WriteHeader(http.StatusNoContent)
fmt.Fprint(w, "")
}