blob: af5821aa7c238ab418c8c91d8f70aeaa4dd7c454 [file] [log] [blame]
Scott Baker2c1c4822019-10-16 11:02:41 -07001/*
Joey Armstrong9cdee9f2024-01-03 04:56:14 -05002 * Copyright 2018-2024 Open Networking Foundation (ONF) and the ONF Contributors
Scott Baker2c1c4822019-10-16 11:02:41 -07003
4 * Licensed under the Apache License, Version 2.0 (the "License");
5 * you may not use this file except in compliance with the License.
6 * You may obtain a copy of the License at
7
8 * http://www.apache.org/licenses/LICENSE-2.0
9
10 * Unless required by applicable law or agreed to in writing, software
11 * distributed under the License is distributed on an "AS IS" BASIS,
12 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13 * See the License for the specific language governing permissions and
14 * limitations under the License.
15 */
16
Girish Kumar950f21e2020-08-19 17:42:29 +000017// Package log provides a structured Logger interface implemented using zap logger. It provides the following capabilities:
18// 1. Package level logging - a go package can register itself (AddPackage) and have a logger created for that package.
19// 2. Dynamic log level change - for all registered packages (SetAllLogLevel)
20// 3. Dynamic log level change - for a given package (SetPackageLogLevel)
21// 4. Provides a default logger for unregistered packages (however avoid its usage)
22// 5. Allow key-value pairs to be added to a logger(UpdateLogger) or all loggers (UpdateAllLoggers) at run time
23// 6. Add to the log output the location where the log was invoked (filename.functionname.linenumber)
Scott Baker2c1c4822019-10-16 11:02:41 -070024//
25// Using package-level logging (recommended approach). In the examples below, log refers to this log package.
Scott Baker2c1c4822019-10-16 11:02:41 -070026//
Girish Kumar950f21e2020-08-19 17:42:29 +000027// 1. In the appropriate package, add the following in the init section of the package (usually in a common.go file)
28// The log level can be changed and any number of default fields can be added as well. The log level specifies
29// the lowest log level that will be in the output while the fields will be automatically added to all log printouts.
30// However, as voltha components re-initialize the log level of each registered package to default initial loglevel
31// passed as CLI argument, the log level passed in RegisterPackage call effectively has no effect.
Scott Baker2c1c4822019-10-16 11:02:41 -070032//
Girish Kumar950f21e2020-08-19 17:42:29 +000033// var logger log.CLogger
34// func init() {
35// logger, err = log.RegisterPackage(log.JSON, log.ErrorLevel, log.Fields{"key1": "value1"})
36// }
Scott Baker2c1c4822019-10-16 11:02:41 -070037//
Girish Kumar950f21e2020-08-19 17:42:29 +000038// 2. In the calling package, use any of the publicly available functions of local package-level logger instance created
39// in previous step. Here is an example to write an Info log with additional fields:
Scott Baker2c1c4822019-10-16 11:02:41 -070040//
Girish Kumar950f21e2020-08-19 17:42:29 +000041// logger.Infow("An example", mylog.Fields{"myStringOutput": "output", "myIntOutput": 2})
Scott Baker2c1c4822019-10-16 11:02:41 -070042//
Girish Kumar950f21e2020-08-19 17:42:29 +000043// 3. To dynamically change the log level, you can use
44// a) SetLogLevel from inside your package or
45// b) SetPackageLogLevel from anywhere or
46// c) SetAllLogLevel from anywhere.
47//
48// Dynamic Loglevel configuration feature also uses SetPackageLogLevel method based on triggers received due to
49// Changes to configured loglevels
Scott Baker2c1c4822019-10-16 11:02:41 -070050
51package log
52
53import (
Girish Kumar46d7c3a2020-05-18 12:06:33 +000054 "context"
Scott Baker2c1c4822019-10-16 11:02:41 -070055 "errors"
56 "fmt"
Scott Baker2c1c4822019-10-16 11:02:41 -070057 "path"
58 "runtime"
59 "strings"
David K. Bainbridgec50d88c2021-04-08 15:47:03 +000060
61 zp "go.uber.org/zap"
62 zc "go.uber.org/zap/zapcore"
Scott Baker2c1c4822019-10-16 11:02:41 -070063)
64
Rohan Agrawal0c62b5d2020-02-04 09:56:21 +000065type LogLevel int8
66
Scott Baker2c1c4822019-10-16 11:02:41 -070067const (
68 // DebugLevel logs a message at debug level
Rohan Agrawal0c62b5d2020-02-04 09:56:21 +000069 DebugLevel = LogLevel(iota)
Scott Baker2c1c4822019-10-16 11:02:41 -070070 // InfoLevel logs a message at info level
71 InfoLevel
72 // WarnLevel logs a message at warning level
73 WarnLevel
74 // ErrorLevel logs a message at error level
75 ErrorLevel
Scott Baker2c1c4822019-10-16 11:02:41 -070076 // FatalLevel logs a message, then calls os.Exit(1).
77 FatalLevel
78)
79
80// CONSOLE formats the log for the console, mostly used during development
81const CONSOLE = "console"
82
83// JSON formats the log using json format, mostly used by an automated logging system consumption
84const JSON = "json"
85
Girish Kumar46d7c3a2020-05-18 12:06:33 +000086// Context Aware Logger represents an abstract logging interface. Any logging implementation used
Scott Baker2c1c4822019-10-16 11:02:41 -070087// will need to abide by this interface
Girish Kumar46d7c3a2020-05-18 12:06:33 +000088type CLogger interface {
89 Debug(context.Context, ...interface{})
90 Debugln(context.Context, ...interface{})
91 Debugf(context.Context, string, ...interface{})
92 Debugw(context.Context, string, Fields)
Scott Baker2c1c4822019-10-16 11:02:41 -070093
Girish Kumar46d7c3a2020-05-18 12:06:33 +000094 Info(context.Context, ...interface{})
95 Infoln(context.Context, ...interface{})
96 Infof(context.Context, string, ...interface{})
97 Infow(context.Context, string, Fields)
Scott Baker2c1c4822019-10-16 11:02:41 -070098
Girish Kumar46d7c3a2020-05-18 12:06:33 +000099 Warn(context.Context, ...interface{})
100 Warnln(context.Context, ...interface{})
101 Warnf(context.Context, string, ...interface{})
102 Warnw(context.Context, string, Fields)
Scott Baker2c1c4822019-10-16 11:02:41 -0700103
Girish Kumar46d7c3a2020-05-18 12:06:33 +0000104 Error(context.Context, ...interface{})
105 Errorln(context.Context, ...interface{})
106 Errorf(context.Context, string, ...interface{})
107 Errorw(context.Context, string, Fields)
Scott Baker2c1c4822019-10-16 11:02:41 -0700108
Girish Kumar46d7c3a2020-05-18 12:06:33 +0000109 Fatal(context.Context, ...interface{})
110 Fatalln(context.Context, ...interface{})
111 Fatalf(context.Context, string, ...interface{})
112 Fatalw(context.Context, string, Fields)
Scott Baker2c1c4822019-10-16 11:02:41 -0700113
Girish Kumar46d7c3a2020-05-18 12:06:33 +0000114 With(Fields) CLogger
Scott Baker2c1c4822019-10-16 11:02:41 -0700115
116 // The following are added to be able to use this logger as a gRPC LoggerV2 if needed
117 //
Girish Kumar46d7c3a2020-05-18 12:06:33 +0000118 Warning(context.Context, ...interface{})
119 Warningln(context.Context, ...interface{})
120 Warningf(context.Context, string, ...interface{})
Scott Baker2c1c4822019-10-16 11:02:41 -0700121
122 // V reports whether verbosity level l is at least the requested verbose level.
Scott Bakerd7c25f42020-02-21 08:12:06 -0800123 V(l LogLevel) bool
khenaidoob332f9b2020-01-16 16:25:26 -0500124
125 //Returns the log level of this specific logger
Rohan Agrawal0c62b5d2020-02-04 09:56:21 +0000126 GetLogLevel() LogLevel
Scott Baker2c1c4822019-10-16 11:02:41 -0700127}
128
129// Fields is used as key-value pairs for structured logging
130type Fields map[string]interface{}
131
Girish Kumar46d7c3a2020-05-18 12:06:33 +0000132var defaultLogger *clogger
Scott Baker2c1c4822019-10-16 11:02:41 -0700133var cfg zp.Config
134
Girish Kumar46d7c3a2020-05-18 12:06:33 +0000135var loggers map[string]*clogger
Scott Baker2c1c4822019-10-16 11:02:41 -0700136var cfgs map[string]zp.Config
137
Girish Kumar46d7c3a2020-05-18 12:06:33 +0000138type clogger struct {
khenaidoob332f9b2020-01-16 16:25:26 -0500139 log *zp.SugaredLogger
140 parent *zp.Logger
141 packageName string
Scott Baker2c1c4822019-10-16 11:02:41 -0700142}
143
Rohan Agrawal0c62b5d2020-02-04 09:56:21 +0000144func logLevelToAtomicLevel(l LogLevel) zp.AtomicLevel {
Scott Baker2c1c4822019-10-16 11:02:41 -0700145 switch l {
146 case DebugLevel:
147 return zp.NewAtomicLevelAt(zc.DebugLevel)
148 case InfoLevel:
149 return zp.NewAtomicLevelAt(zc.InfoLevel)
150 case WarnLevel:
151 return zp.NewAtomicLevelAt(zc.WarnLevel)
152 case ErrorLevel:
153 return zp.NewAtomicLevelAt(zc.ErrorLevel)
Scott Baker2c1c4822019-10-16 11:02:41 -0700154 case FatalLevel:
155 return zp.NewAtomicLevelAt(zc.FatalLevel)
156 }
157 return zp.NewAtomicLevelAt(zc.ErrorLevel)
158}
159
Rohan Agrawal0c62b5d2020-02-04 09:56:21 +0000160func logLevelToLevel(l LogLevel) zc.Level {
Scott Baker2c1c4822019-10-16 11:02:41 -0700161 switch l {
162 case DebugLevel:
163 return zc.DebugLevel
164 case InfoLevel:
165 return zc.InfoLevel
166 case WarnLevel:
167 return zc.WarnLevel
168 case ErrorLevel:
169 return zc.ErrorLevel
Scott Baker2c1c4822019-10-16 11:02:41 -0700170 case FatalLevel:
171 return zc.FatalLevel
172 }
173 return zc.ErrorLevel
174}
175
Rohan Agrawal0c62b5d2020-02-04 09:56:21 +0000176func levelToLogLevel(l zc.Level) LogLevel {
Scott Baker2c1c4822019-10-16 11:02:41 -0700177 switch l {
178 case zc.DebugLevel:
179 return DebugLevel
180 case zc.InfoLevel:
181 return InfoLevel
182 case zc.WarnLevel:
183 return WarnLevel
184 case zc.ErrorLevel:
185 return ErrorLevel
Rohan Agrawal6a99a452020-01-14 07:58:25 +0000186 case zc.FatalLevel:
187 return FatalLevel
188 }
189 return ErrorLevel
190}
191
Rohan Agrawal0c62b5d2020-02-04 09:56:21 +0000192func StringToLogLevel(l string) (LogLevel, error) {
193 switch strings.ToUpper(l) {
Rohan Agrawal6a99a452020-01-14 07:58:25 +0000194 case "DEBUG":
Rohan Agrawal0c62b5d2020-02-04 09:56:21 +0000195 return DebugLevel, nil
Rohan Agrawal6a99a452020-01-14 07:58:25 +0000196 case "INFO":
Rohan Agrawal0c62b5d2020-02-04 09:56:21 +0000197 return InfoLevel, nil
Rohan Agrawal6a99a452020-01-14 07:58:25 +0000198 case "WARN":
Rohan Agrawal0c62b5d2020-02-04 09:56:21 +0000199 return WarnLevel, nil
Rohan Agrawal6a99a452020-01-14 07:58:25 +0000200 case "ERROR":
Rohan Agrawal0c62b5d2020-02-04 09:56:21 +0000201 return ErrorLevel, nil
Rohan Agrawal6a99a452020-01-14 07:58:25 +0000202 case "FATAL":
Rohan Agrawal0c62b5d2020-02-04 09:56:21 +0000203 return FatalLevel, nil
Scott Baker2c1c4822019-10-16 11:02:41 -0700204 }
Rohan Agrawal0c62b5d2020-02-04 09:56:21 +0000205 return 0, errors.New("Given LogLevel is invalid : " + l)
Scott Baker2c1c4822019-10-16 11:02:41 -0700206}
207
divyadesai8bf96862020-02-07 12:24:26 +0000208func LogLevelToString(l LogLevel) (string, error) {
209 switch l {
210 case DebugLevel:
211 return "DEBUG", nil
212 case InfoLevel:
213 return "INFO", nil
214 case WarnLevel:
215 return "WARN", nil
216 case ErrorLevel:
217 return "ERROR", nil
218 case FatalLevel:
219 return "FATAL", nil
220 }
David K. Bainbridgec50d88c2021-04-08 15:47:03 +0000221 return "", fmt.Errorf("Given LogLevel is invalid %d", l)
divyadesai8bf96862020-02-07 12:24:26 +0000222}
223
Rohan Agrawal0c62b5d2020-02-04 09:56:21 +0000224func getDefaultConfig(outputType string, level LogLevel, defaultFields Fields) zp.Config {
Scott Baker2c1c4822019-10-16 11:02:41 -0700225 return zp.Config{
Rohan Agrawal0c62b5d2020-02-04 09:56:21 +0000226 Level: logLevelToAtomicLevel(level),
Scott Baker2c1c4822019-10-16 11:02:41 -0700227 Encoding: outputType,
228 Development: true,
229 OutputPaths: []string{"stdout"},
230 ErrorOutputPaths: []string{"stderr"},
231 InitialFields: defaultFields,
232 EncoderConfig: zc.EncoderConfig{
233 LevelKey: "level",
234 MessageKey: "msg",
235 TimeKey: "ts",
Girish Kumarc9b0e712020-02-27 17:50:52 +0000236 CallerKey: "caller",
Scott Baker2c1c4822019-10-16 11:02:41 -0700237 StacktraceKey: "stacktrace",
238 LineEnding: zc.DefaultLineEnding,
239 EncodeLevel: zc.LowercaseLevelEncoder,
240 EncodeTime: zc.ISO8601TimeEncoder,
241 EncodeDuration: zc.SecondsDurationEncoder,
242 EncodeCaller: zc.ShortCallerEncoder,
243 },
244 }
245}
246
Rohan Agrawalee87e642020-04-14 10:22:18 +0000247func ConstructZapConfig(outputType string, level LogLevel, fields Fields) zp.Config {
248 return getDefaultConfig(outputType, level, fields)
249}
250
Scott Baker2c1c4822019-10-16 11:02:41 -0700251// SetLogger needs to be invoked before the logger API can be invoked. This function
252// initialize the default logger (zap's sugaredlogger)
Girish Kumar46d7c3a2020-05-18 12:06:33 +0000253func SetDefaultLogger(outputType string, level LogLevel, defaultFields Fields) (CLogger, error) {
Scott Baker2c1c4822019-10-16 11:02:41 -0700254 // Build a custom config using zap
255 cfg = getDefaultConfig(outputType, level, defaultFields)
256
Girish Kumarc9b0e712020-02-27 17:50:52 +0000257 l, err := cfg.Build(zp.AddCallerSkip(1))
Scott Baker2c1c4822019-10-16 11:02:41 -0700258 if err != nil {
259 return nil, err
260 }
261
Girish Kumar46d7c3a2020-05-18 12:06:33 +0000262 defaultLogger = &clogger{
Scott Baker2c1c4822019-10-16 11:02:41 -0700263 log: l.Sugar(),
264 parent: l,
265 }
266
267 return defaultLogger, nil
268}
269
270// AddPackage registers a package to the log map. Each package gets its own logger which allows
271// its config (loglevel) to be changed dynamically without interacting with the other packages.
272// outputType is JSON, level is the lowest level log to output with this logger and defaultFields is a map of
273// key-value pairs to always add to the output.
274// Note: AddPackage also returns a reference to the actual logger. If a calling package uses this reference directly
Joey Armstrong7f8436c2023-07-09 20:23:27 -0400275// instead of using the publicly available functions in this log package then a number of functionalities will not
Scott Baker2c1c4822019-10-16 11:02:41 -0700276// be available to it, notably log tracing with filename.functionname.linenumber annotation.
277//
278// pkgNames parameter should be used for testing only as this function detects the caller's package.
Girish Kumar46d7c3a2020-05-18 12:06:33 +0000279func RegisterPackage(outputType string, level LogLevel, defaultFields Fields, pkgNames ...string) (CLogger, error) {
Scott Baker2c1c4822019-10-16 11:02:41 -0700280 if cfgs == nil {
281 cfgs = make(map[string]zp.Config)
282 }
283 if loggers == nil {
Girish Kumar46d7c3a2020-05-18 12:06:33 +0000284 loggers = make(map[string]*clogger)
Scott Baker2c1c4822019-10-16 11:02:41 -0700285 }
286
287 var pkgName string
288 for _, name := range pkgNames {
289 pkgName = name
290 break
291 }
292 if pkgName == "" {
293 pkgName, _, _, _ = getCallerInfo()
294 }
295
296 if _, exist := loggers[pkgName]; exist {
297 return loggers[pkgName], nil
298 }
299
300 cfgs[pkgName] = getDefaultConfig(outputType, level, defaultFields)
301
Girish Kumarc9b0e712020-02-27 17:50:52 +0000302 l, err := cfgs[pkgName].Build(zp.AddCallerSkip(1))
Scott Baker2c1c4822019-10-16 11:02:41 -0700303 if err != nil {
304 return nil, err
305 }
306
Girish Kumar46d7c3a2020-05-18 12:06:33 +0000307 loggers[pkgName] = &clogger{
khenaidoob332f9b2020-01-16 16:25:26 -0500308 log: l.Sugar(),
309 parent: l,
310 packageName: pkgName,
Scott Baker2c1c4822019-10-16 11:02:41 -0700311 }
312 return loggers[pkgName], nil
313}
314
Joey Armstrong7f8436c2023-07-09 20:23:27 -0400315// UpdateAllLoggers create new loggers for all registered pacakges with the defaultFields.
Scott Baker2c1c4822019-10-16 11:02:41 -0700316func UpdateAllLoggers(defaultFields Fields) error {
317 for pkgName, cfg := range cfgs {
318 for k, v := range defaultFields {
319 if cfg.InitialFields == nil {
320 cfg.InitialFields = make(map[string]interface{})
321 }
322 cfg.InitialFields[k] = v
323 }
Girish Kumarc9b0e712020-02-27 17:50:52 +0000324 l, err := cfg.Build(zp.AddCallerSkip(1))
Scott Baker2c1c4822019-10-16 11:02:41 -0700325 if err != nil {
326 return err
327 }
328
Girish Kumarc9b0e712020-02-27 17:50:52 +0000329 // Update the existing zap logger instance
330 loggers[pkgName].log = l.Sugar()
331 loggers[pkgName].parent = l
Scott Baker2c1c4822019-10-16 11:02:41 -0700332 }
333 return nil
334}
335
336// Return a list of all packages that have individually-configured loggers
337func GetPackageNames() []string {
338 i := 0
339 keys := make([]string, len(loggers))
340 for k := range loggers {
341 keys[i] = k
342 i++
343 }
344 return keys
345}
346
Girish Kumarc9b0e712020-02-27 17:50:52 +0000347// UpdateLogger updates the logger associated with a caller's package with supplied defaultFields
348func UpdateLogger(defaultFields Fields) error {
Scott Baker2c1c4822019-10-16 11:02:41 -0700349 pkgName, _, _, _ := getCallerInfo()
350 if _, exist := loggers[pkgName]; !exist {
Girish Kumarc9b0e712020-02-27 17:50:52 +0000351 return fmt.Errorf("package-%s-not-registered", pkgName)
Scott Baker2c1c4822019-10-16 11:02:41 -0700352 }
353
354 // Build a new logger
355 if _, exist := cfgs[pkgName]; !exist {
Girish Kumarc9b0e712020-02-27 17:50:52 +0000356 return fmt.Errorf("config-%s-not-registered", pkgName)
Scott Baker2c1c4822019-10-16 11:02:41 -0700357 }
358
359 cfg := cfgs[pkgName]
360 for k, v := range defaultFields {
361 if cfg.InitialFields == nil {
362 cfg.InitialFields = make(map[string]interface{})
363 }
364 cfg.InitialFields[k] = v
365 }
Girish Kumarc9b0e712020-02-27 17:50:52 +0000366 l, err := cfg.Build(zp.AddCallerSkip(1))
Scott Baker2c1c4822019-10-16 11:02:41 -0700367 if err != nil {
Girish Kumarc9b0e712020-02-27 17:50:52 +0000368 return err
Scott Baker2c1c4822019-10-16 11:02:41 -0700369 }
370
Girish Kumarc9b0e712020-02-27 17:50:52 +0000371 // Update the existing zap logger instance
372 loggers[pkgName].log = l.Sugar()
373 loggers[pkgName].parent = l
374
375 return nil
Scott Baker2c1c4822019-10-16 11:02:41 -0700376}
377
Rohan Agrawal0c62b5d2020-02-04 09:56:21 +0000378func setLevel(cfg zp.Config, level LogLevel) {
Scott Baker2c1c4822019-10-16 11:02:41 -0700379 switch level {
380 case DebugLevel:
381 cfg.Level.SetLevel(zc.DebugLevel)
382 case InfoLevel:
383 cfg.Level.SetLevel(zc.InfoLevel)
384 case WarnLevel:
385 cfg.Level.SetLevel(zc.WarnLevel)
386 case ErrorLevel:
387 cfg.Level.SetLevel(zc.ErrorLevel)
Scott Baker2c1c4822019-10-16 11:02:41 -0700388 case FatalLevel:
389 cfg.Level.SetLevel(zc.FatalLevel)
390 default:
391 cfg.Level.SetLevel(zc.ErrorLevel)
392 }
393}
394
Joey Armstrong7f8436c2023-07-09 20:23:27 -0400395// SetPackageLogLevel dynamically sets the log level of a given package to level. This is typically invoked at an
Scott Baker2c1c4822019-10-16 11:02:41 -0700396// application level during debugging
Rohan Agrawal0c62b5d2020-02-04 09:56:21 +0000397func SetPackageLogLevel(packageName string, level LogLevel) {
Scott Baker2c1c4822019-10-16 11:02:41 -0700398 // Get proper config
399 if cfg, ok := cfgs[packageName]; ok {
400 setLevel(cfg, level)
401 }
402}
403
Joey Armstrong7f8436c2023-07-09 20:23:27 -0400404// SetAllLogLevel sets the log level of all registered packages to level
Rohan Agrawal0c62b5d2020-02-04 09:56:21 +0000405func SetAllLogLevel(level LogLevel) {
Scott Baker2c1c4822019-10-16 11:02:41 -0700406 // Get proper config
407 for _, cfg := range cfgs {
408 setLevel(cfg, level)
409 }
410}
411
Joey Armstrong7f8436c2023-07-09 20:23:27 -0400412// GetPackageLogLevel returns the current log level of a package.
Rohan Agrawal0c62b5d2020-02-04 09:56:21 +0000413func GetPackageLogLevel(packageName ...string) (LogLevel, error) {
Scott Baker2c1c4822019-10-16 11:02:41 -0700414 var name string
415 if len(packageName) == 1 {
416 name = packageName[0]
417 } else {
418 name, _, _, _ = getCallerInfo()
419 }
420 if cfg, ok := cfgs[name]; ok {
Rohan Agrawal0c62b5d2020-02-04 09:56:21 +0000421 return levelToLogLevel(cfg.Level.Level()), nil
Scott Baker2c1c4822019-10-16 11:02:41 -0700422 }
David K. Bainbridge7c75cac2020-02-19 08:53:46 -0800423 return 0, fmt.Errorf("unknown-package-%s", name)
Scott Baker2c1c4822019-10-16 11:02:41 -0700424}
425
Joey Armstrong7f8436c2023-07-09 20:23:27 -0400426// GetDefaultLogLevel gets the log level used for packages that don't have specific loggers
Rohan Agrawal0c62b5d2020-02-04 09:56:21 +0000427func GetDefaultLogLevel() LogLevel {
428 return levelToLogLevel(cfg.Level.Level())
Scott Baker2c1c4822019-10-16 11:02:41 -0700429}
430
Joey Armstrong7f8436c2023-07-09 20:23:27 -0400431// SetLogLevel sets the log level for the logger corresponding to the caller's package
Rohan Agrawal0c62b5d2020-02-04 09:56:21 +0000432func SetLogLevel(level LogLevel) error {
Scott Baker2c1c4822019-10-16 11:02:41 -0700433 pkgName, _, _, _ := getCallerInfo()
434 if _, exist := cfgs[pkgName]; !exist {
David K. Bainbridge7c75cac2020-02-19 08:53:46 -0800435 return fmt.Errorf("unregistered-package-%s", pkgName)
Scott Baker2c1c4822019-10-16 11:02:41 -0700436 }
437 cfg := cfgs[pkgName]
438 setLevel(cfg, level)
439 return nil
440}
441
Joey Armstrong7f8436c2023-07-09 20:23:27 -0400442// SetDefaultLogLevel sets the log level used for packages that don't have specific loggers
Rohan Agrawal0c62b5d2020-02-04 09:56:21 +0000443func SetDefaultLogLevel(level LogLevel) {
Scott Baker2c1c4822019-10-16 11:02:41 -0700444 setLevel(cfg, level)
445}
446
447// CleanUp flushed any buffered log entries. Applications should take care to call
448// CleanUp before exiting.
449func CleanUp() error {
450 for _, logger := range loggers {
451 if logger != nil {
452 if logger.parent != nil {
453 if err := logger.parent.Sync(); err != nil {
454 return err
455 }
456 }
457 }
458 }
459 if defaultLogger != nil {
460 if defaultLogger.parent != nil {
461 if err := defaultLogger.parent.Sync(); err != nil {
462 return err
463 }
464 }
465 }
466 return nil
467}
468
469func getCallerInfo() (string, string, string, int) {
470 // Since the caller of a log function is one stack frame before (in terms of stack higher level) the log.go
471 // filename, then first look for the last log.go filename and then grab the caller info one level higher.
472 maxLevel := 3
473 skiplevel := 3 // Level with the most empirical success to see the last log.go stack frame.
474 pc := make([]uintptr, maxLevel)
475 n := runtime.Callers(skiplevel, pc)
476 packageName := ""
477 funcName := ""
478 fileName := ""
479 var line int
480 if n == 0 {
481 return packageName, fileName, funcName, line
482 }
483 frames := runtime.CallersFrames(pc[:n])
484 var frame runtime.Frame
485 var foundFrame runtime.Frame
486 more := true
487 for more {
488 frame, more = frames.Next()
489 _, fileName = path.Split(frame.File)
490 if fileName != "log.go" {
491 foundFrame = frame // First frame after log.go in the frame stack
492 break
493 }
494 }
495 parts := strings.Split(foundFrame.Function, ".")
496 pl := len(parts)
497 if pl >= 2 {
498 funcName = parts[pl-1]
499 if parts[pl-2][0] == '(' {
500 packageName = strings.Join(parts[0:pl-2], ".")
501 } else {
502 packageName = strings.Join(parts[0:pl-1], ".")
503 }
504 }
505
506 if strings.HasSuffix(packageName, ".init") {
507 packageName = strings.TrimSuffix(packageName, ".init")
508 }
509
510 if strings.HasSuffix(fileName, ".go") {
511 fileName = strings.TrimSuffix(fileName, ".go")
512 }
513
514 return packageName, fileName, funcName, foundFrame.Line
515}
516
Scott Baker2c1c4822019-10-16 11:02:41 -0700517// With returns a logger initialized with the key-value pairs
Girish Kumar46d7c3a2020-05-18 12:06:33 +0000518func (l clogger) With(keysAndValues Fields) CLogger {
519 return clogger{log: l.log.With(serializeMap(keysAndValues)...), parent: l.parent}
Scott Baker2c1c4822019-10-16 11:02:41 -0700520}
521
522// Debug logs a message at level Debug on the standard logger.
Girish Kumar46d7c3a2020-05-18 12:06:33 +0000523func (l clogger) Debug(ctx context.Context, args ...interface{}) {
Girish Kumar503cce62020-08-24 16:34:39 +0000524 l.log.With(GetGlobalLFM().ExtractContextAttributes(ctx)...).Debug(args...)
Scott Baker2c1c4822019-10-16 11:02:41 -0700525}
526
527// Debugln logs a message at level Debug on the standard logger with a line feed. Default in any case.
Girish Kumar46d7c3a2020-05-18 12:06:33 +0000528func (l clogger) Debugln(ctx context.Context, args ...interface{}) {
Girish Kumar503cce62020-08-24 16:34:39 +0000529 l.log.With(GetGlobalLFM().ExtractContextAttributes(ctx)...).Debug(args...)
Scott Baker2c1c4822019-10-16 11:02:41 -0700530}
531
532// Debugw logs a message at level Debug on the standard logger.
Girish Kumar46d7c3a2020-05-18 12:06:33 +0000533func (l clogger) Debugf(ctx context.Context, format string, args ...interface{}) {
Girish Kumar503cce62020-08-24 16:34:39 +0000534 l.log.With(GetGlobalLFM().ExtractContextAttributes(ctx)...).Debugf(format, args...)
Scott Baker2c1c4822019-10-16 11:02:41 -0700535}
536
537// Debugw logs a message with some additional context. The variadic key-value
538// pairs are treated as they are in With.
Girish Kumar46d7c3a2020-05-18 12:06:33 +0000539func (l clogger) Debugw(ctx context.Context, msg string, keysAndValues Fields) {
khenaidoob3ec7d52020-04-29 16:52:08 -0400540 if l.V(DebugLevel) {
Girish Kumar503cce62020-08-24 16:34:39 +0000541 l.log.With(GetGlobalLFM().ExtractContextAttributes(ctx)...).Debugw(msg, serializeMap(keysAndValues)...)
khenaidoob3ec7d52020-04-29 16:52:08 -0400542 }
Scott Baker2c1c4822019-10-16 11:02:41 -0700543}
544
545// Info logs a message at level Info on the standard logger.
Girish Kumar46d7c3a2020-05-18 12:06:33 +0000546func (l clogger) Info(ctx context.Context, args ...interface{}) {
Girish Kumar503cce62020-08-24 16:34:39 +0000547 l.log.With(GetGlobalLFM().ExtractContextAttributes(ctx)...).Info(args...)
Scott Baker2c1c4822019-10-16 11:02:41 -0700548}
549
550// Infoln logs a message at level Info on the standard logger with a line feed. Default in any case.
Girish Kumar46d7c3a2020-05-18 12:06:33 +0000551func (l clogger) Infoln(ctx context.Context, args ...interface{}) {
Girish Kumar503cce62020-08-24 16:34:39 +0000552 l.log.With(GetGlobalLFM().ExtractContextAttributes(ctx)...).Info(args...)
Scott Baker2c1c4822019-10-16 11:02:41 -0700553 //msg := fmt.Sprintln(args...)
554 //l.sourced().Info(msg[:len(msg)-1])
555}
556
557// Infof logs a message at level Info on the standard logger.
Girish Kumar46d7c3a2020-05-18 12:06:33 +0000558func (l clogger) Infof(ctx context.Context, format string, args ...interface{}) {
Girish Kumar503cce62020-08-24 16:34:39 +0000559 l.log.With(GetGlobalLFM().ExtractContextAttributes(ctx)...).Infof(format, args...)
Scott Baker2c1c4822019-10-16 11:02:41 -0700560}
561
562// Infow logs a message with some additional context. The variadic key-value
563// pairs are treated as they are in With.
Girish Kumar46d7c3a2020-05-18 12:06:33 +0000564func (l clogger) Infow(ctx context.Context, msg string, keysAndValues Fields) {
khenaidoob3ec7d52020-04-29 16:52:08 -0400565 if l.V(InfoLevel) {
Girish Kumar503cce62020-08-24 16:34:39 +0000566 l.log.With(GetGlobalLFM().ExtractContextAttributes(ctx)...).Infow(msg, serializeMap(keysAndValues)...)
khenaidoob3ec7d52020-04-29 16:52:08 -0400567 }
Scott Baker2c1c4822019-10-16 11:02:41 -0700568}
569
570// Warn logs a message at level Warn on the standard logger.
Girish Kumar46d7c3a2020-05-18 12:06:33 +0000571func (l clogger) Warn(ctx context.Context, args ...interface{}) {
Girish Kumar503cce62020-08-24 16:34:39 +0000572 l.log.With(GetGlobalLFM().ExtractContextAttributes(ctx)...).Warn(args...)
Scott Baker2c1c4822019-10-16 11:02:41 -0700573}
574
575// Warnln logs a message at level Warn on the standard logger with a line feed. Default in any case.
Girish Kumar46d7c3a2020-05-18 12:06:33 +0000576func (l clogger) Warnln(ctx context.Context, args ...interface{}) {
Girish Kumar503cce62020-08-24 16:34:39 +0000577 l.log.With(GetGlobalLFM().ExtractContextAttributes(ctx)...).Warn(args...)
Scott Baker2c1c4822019-10-16 11:02:41 -0700578}
579
580// Warnf logs a message at level Warn on the standard logger.
Girish Kumar46d7c3a2020-05-18 12:06:33 +0000581func (l clogger) Warnf(ctx context.Context, format string, args ...interface{}) {
Girish Kumar503cce62020-08-24 16:34:39 +0000582 l.log.With(GetGlobalLFM().ExtractContextAttributes(ctx)...).Warnf(format, args...)
Scott Baker2c1c4822019-10-16 11:02:41 -0700583}
584
585// Warnw logs a message with some additional context. The variadic key-value
586// pairs are treated as they are in With.
Girish Kumar46d7c3a2020-05-18 12:06:33 +0000587func (l clogger) Warnw(ctx context.Context, msg string, keysAndValues Fields) {
khenaidoob3ec7d52020-04-29 16:52:08 -0400588 if l.V(WarnLevel) {
Girish Kumar503cce62020-08-24 16:34:39 +0000589 l.log.With(GetGlobalLFM().ExtractContextAttributes(ctx)...).Warnw(msg, serializeMap(keysAndValues)...)
khenaidoob3ec7d52020-04-29 16:52:08 -0400590 }
Scott Baker2c1c4822019-10-16 11:02:41 -0700591}
592
593// Error logs a message at level Error on the standard logger.
Girish Kumar46d7c3a2020-05-18 12:06:33 +0000594func (l clogger) Error(ctx context.Context, args ...interface{}) {
Girish Kumar503cce62020-08-24 16:34:39 +0000595 l.log.With(GetGlobalLFM().ExtractContextAttributes(ctx)...).Error(args...)
Scott Baker2c1c4822019-10-16 11:02:41 -0700596}
597
598// Errorln logs a message at level Error on the standard logger with a line feed. Default in any case.
Girish Kumar46d7c3a2020-05-18 12:06:33 +0000599func (l clogger) Errorln(ctx context.Context, args ...interface{}) {
Girish Kumar503cce62020-08-24 16:34:39 +0000600 l.log.With(GetGlobalLFM().ExtractContextAttributes(ctx)...).Error(args...)
Scott Baker2c1c4822019-10-16 11:02:41 -0700601}
602
603// Errorf logs a message at level Error on the standard logger.
Girish Kumar46d7c3a2020-05-18 12:06:33 +0000604func (l clogger) Errorf(ctx context.Context, format string, args ...interface{}) {
Girish Kumar503cce62020-08-24 16:34:39 +0000605 l.log.With(GetGlobalLFM().ExtractContextAttributes(ctx)...).Errorf(format, args...)
Scott Baker2c1c4822019-10-16 11:02:41 -0700606}
607
608// Errorw logs a message with some additional context. The variadic key-value
609// pairs are treated as they are in With.
Girish Kumar46d7c3a2020-05-18 12:06:33 +0000610func (l clogger) Errorw(ctx context.Context, msg string, keysAndValues Fields) {
khenaidoob3ec7d52020-04-29 16:52:08 -0400611 if l.V(ErrorLevel) {
Girish Kumar503cce62020-08-24 16:34:39 +0000612 l.log.With(GetGlobalLFM().ExtractContextAttributes(ctx)...).Errorw(msg, serializeMap(keysAndValues)...)
khenaidoob3ec7d52020-04-29 16:52:08 -0400613 }
Scott Baker2c1c4822019-10-16 11:02:41 -0700614}
615
616// Fatal logs a message at level Fatal on the standard logger.
Girish Kumar46d7c3a2020-05-18 12:06:33 +0000617func (l clogger) Fatal(ctx context.Context, args ...interface{}) {
Girish Kumar503cce62020-08-24 16:34:39 +0000618 l.log.With(GetGlobalLFM().ExtractContextAttributes(ctx)...).Fatal(args...)
Scott Baker2c1c4822019-10-16 11:02:41 -0700619}
620
621// Fatalln logs a message at level Fatal on the standard logger with a line feed. Default in any case.
Girish Kumar46d7c3a2020-05-18 12:06:33 +0000622func (l clogger) Fatalln(ctx context.Context, args ...interface{}) {
Girish Kumar503cce62020-08-24 16:34:39 +0000623 l.log.With(GetGlobalLFM().ExtractContextAttributes(ctx)...).Fatal(args...)
Scott Baker2c1c4822019-10-16 11:02:41 -0700624}
625
626// Fatalf logs a message at level Fatal on the standard logger.
Girish Kumar46d7c3a2020-05-18 12:06:33 +0000627func (l clogger) Fatalf(ctx context.Context, format string, args ...interface{}) {
Girish Kumar503cce62020-08-24 16:34:39 +0000628 l.log.With(GetGlobalLFM().ExtractContextAttributes(ctx)...).Fatalf(format, args...)
Scott Baker2c1c4822019-10-16 11:02:41 -0700629}
630
631// Fatalw logs a message with some additional context. The variadic key-value
632// pairs are treated as they are in With.
Girish Kumar46d7c3a2020-05-18 12:06:33 +0000633func (l clogger) Fatalw(ctx context.Context, msg string, keysAndValues Fields) {
khenaidoob3ec7d52020-04-29 16:52:08 -0400634 if l.V(FatalLevel) {
Girish Kumar503cce62020-08-24 16:34:39 +0000635 l.log.With(GetGlobalLFM().ExtractContextAttributes(ctx)...).Fatalw(msg, serializeMap(keysAndValues)...)
khenaidoob3ec7d52020-04-29 16:52:08 -0400636 }
Scott Baker2c1c4822019-10-16 11:02:41 -0700637}
638
639// Warning logs a message at level Warn on the standard logger.
Girish Kumar46d7c3a2020-05-18 12:06:33 +0000640func (l clogger) Warning(ctx context.Context, args ...interface{}) {
Girish Kumar503cce62020-08-24 16:34:39 +0000641 l.log.With(GetGlobalLFM().ExtractContextAttributes(ctx)...).Warn(args...)
Scott Baker2c1c4822019-10-16 11:02:41 -0700642}
643
644// Warningln logs a message at level Warn on the standard logger with a line feed. Default in any case.
Girish Kumar46d7c3a2020-05-18 12:06:33 +0000645func (l clogger) Warningln(ctx context.Context, args ...interface{}) {
Girish Kumar503cce62020-08-24 16:34:39 +0000646 l.log.With(GetGlobalLFM().ExtractContextAttributes(ctx)...).Warn(args...)
Scott Baker2c1c4822019-10-16 11:02:41 -0700647}
648
649// Warningf logs a message at level Warn on the standard logger.
Girish Kumar46d7c3a2020-05-18 12:06:33 +0000650func (l clogger) Warningf(ctx context.Context, format string, args ...interface{}) {
Girish Kumar503cce62020-08-24 16:34:39 +0000651 l.log.With(GetGlobalLFM().ExtractContextAttributes(ctx)...).Warnf(format, args...)
Scott Baker2c1c4822019-10-16 11:02:41 -0700652}
653
654// V reports whether verbosity level l is at least the requested verbose level.
Girish Kumar46d7c3a2020-05-18 12:06:33 +0000655func (l clogger) V(level LogLevel) bool {
Scott Bakerd7c25f42020-02-21 08:12:06 -0800656 return l.parent.Core().Enabled(logLevelToLevel(level))
Scott Baker2c1c4822019-10-16 11:02:41 -0700657}
658
khenaidoob332f9b2020-01-16 16:25:26 -0500659// GetLogLevel returns the current level of the logger
Girish Kumar46d7c3a2020-05-18 12:06:33 +0000660func (l clogger) GetLogLevel() LogLevel {
Rohan Agrawal0c62b5d2020-02-04 09:56:21 +0000661 return levelToLogLevel(cfgs[l.packageName].Level.Level())
khenaidoob332f9b2020-01-16 16:25:26 -0500662}
Tinoj Josephe4e80d62022-07-15 16:31:43 +0530663
Joey Armstrong7f8436c2023-07-09 20:23:27 -0400664// UpdateCallerSkipLevel create new loggers for specified registered pacakges with the default updated caller skipltFields.
665// This will enable to skip wrapper file caller in caller info and stacktrace
Tinoj Josephe4e80d62022-07-15 16:31:43 +0530666func UpdateCallerSkipLevel(skipLevel int) (CLogger, error) {
667 pkgName, _, _, _ := getCallerInfo()
668 if cfg, exist := cfgs[pkgName]; exist {
669 l, err := cfg.Build(zp.AddCallerSkip(skipLevel))
670 if err != nil {
671 return loggers[pkgName], err
672 }
673
674 // Update the existing zap logger instance
675 loggers[pkgName].log = l.Sugar()
676 loggers[pkgName].parent = l
677
678 return loggers[pkgName], nil
679 }
680
681 return loggers[pkgName], errors.New("Package Not Found")
682}
683
Joey Armstrong7f8436c2023-07-09 20:23:27 -0400684// UpdateAllCallerSkipLevel create new loggers for all registered pacakges with the default updated caller skipltFields.
685// This will enable to skip wrapper file caller in caller info and stacktrace
Tinoj Josephe4e80d62022-07-15 16:31:43 +0530686func UpdateAllCallerSkipLevel(skipLevel int) error {
687 for pkgName, cfg := range cfgs {
688 l, err := cfg.Build(zp.AddCallerSkip(skipLevel))
689 if err != nil {
690 return err
691 }
692
693 // Update the existing zap logger instance
694 loggers[pkgName].log = l.Sugar()
695 loggers[pkgName].parent = l
696 }
697 return nil
698}