blob: b8d498c820a71bdeb81d258c964ae1bfad6bc63e [file] [log] [blame]
Scott Baker2c1c4822019-10-16 11:02:41 -07001/*
2 * Copyright 2018-present Open Networking Foundation
3
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"
57 zp "go.uber.org/zap"
58 zc "go.uber.org/zap/zapcore"
59 "path"
60 "runtime"
61 "strings"
62)
63
Rohan Agrawal0c62b5d2020-02-04 09:56:21 +000064type LogLevel int8
65
Scott Baker2c1c4822019-10-16 11:02:41 -070066const (
67 // DebugLevel logs a message at debug level
Rohan Agrawal0c62b5d2020-02-04 09:56:21 +000068 DebugLevel = LogLevel(iota)
Scott Baker2c1c4822019-10-16 11:02:41 -070069 // InfoLevel logs a message at info level
70 InfoLevel
71 // WarnLevel logs a message at warning level
72 WarnLevel
73 // ErrorLevel logs a message at error level
74 ErrorLevel
Scott Baker2c1c4822019-10-16 11:02:41 -070075 // FatalLevel logs a message, then calls os.Exit(1).
76 FatalLevel
77)
78
79// CONSOLE formats the log for the console, mostly used during development
80const CONSOLE = "console"
81
82// JSON formats the log using json format, mostly used by an automated logging system consumption
83const JSON = "json"
84
Girish Kumar46d7c3a2020-05-18 12:06:33 +000085// Context Aware Logger represents an abstract logging interface. Any logging implementation used
Scott Baker2c1c4822019-10-16 11:02:41 -070086// will need to abide by this interface
Girish Kumar46d7c3a2020-05-18 12:06:33 +000087type CLogger interface {
88 Debug(context.Context, ...interface{})
89 Debugln(context.Context, ...interface{})
90 Debugf(context.Context, string, ...interface{})
91 Debugw(context.Context, string, Fields)
Scott Baker2c1c4822019-10-16 11:02:41 -070092
Girish Kumar46d7c3a2020-05-18 12:06:33 +000093 Info(context.Context, ...interface{})
94 Infoln(context.Context, ...interface{})
95 Infof(context.Context, string, ...interface{})
96 Infow(context.Context, string, Fields)
Scott Baker2c1c4822019-10-16 11:02:41 -070097
Girish Kumar46d7c3a2020-05-18 12:06:33 +000098 Warn(context.Context, ...interface{})
99 Warnln(context.Context, ...interface{})
100 Warnf(context.Context, string, ...interface{})
101 Warnw(context.Context, string, Fields)
Scott Baker2c1c4822019-10-16 11:02:41 -0700102
Girish Kumar46d7c3a2020-05-18 12:06:33 +0000103 Error(context.Context, ...interface{})
104 Errorln(context.Context, ...interface{})
105 Errorf(context.Context, string, ...interface{})
106 Errorw(context.Context, string, Fields)
Scott Baker2c1c4822019-10-16 11:02:41 -0700107
Girish Kumar46d7c3a2020-05-18 12:06:33 +0000108 Fatal(context.Context, ...interface{})
109 Fatalln(context.Context, ...interface{})
110 Fatalf(context.Context, string, ...interface{})
111 Fatalw(context.Context, string, Fields)
Scott Baker2c1c4822019-10-16 11:02:41 -0700112
Girish Kumar46d7c3a2020-05-18 12:06:33 +0000113 With(Fields) CLogger
Scott Baker2c1c4822019-10-16 11:02:41 -0700114
115 // The following are added to be able to use this logger as a gRPC LoggerV2 if needed
116 //
Girish Kumar46d7c3a2020-05-18 12:06:33 +0000117 Warning(context.Context, ...interface{})
118 Warningln(context.Context, ...interface{})
119 Warningf(context.Context, string, ...interface{})
Scott Baker2c1c4822019-10-16 11:02:41 -0700120
121 // V reports whether verbosity level l is at least the requested verbose level.
Scott Bakerd7c25f42020-02-21 08:12:06 -0800122 V(l LogLevel) bool
khenaidoob332f9b2020-01-16 16:25:26 -0500123
124 //Returns the log level of this specific logger
Rohan Agrawal0c62b5d2020-02-04 09:56:21 +0000125 GetLogLevel() LogLevel
Scott Baker2c1c4822019-10-16 11:02:41 -0700126}
127
128// Fields is used as key-value pairs for structured logging
129type Fields map[string]interface{}
130
Girish Kumar46d7c3a2020-05-18 12:06:33 +0000131var defaultLogger *clogger
Scott Baker2c1c4822019-10-16 11:02:41 -0700132var cfg zp.Config
133
Girish Kumar46d7c3a2020-05-18 12:06:33 +0000134var loggers map[string]*clogger
Scott Baker2c1c4822019-10-16 11:02:41 -0700135var cfgs map[string]zp.Config
136
Girish Kumar46d7c3a2020-05-18 12:06:33 +0000137type clogger struct {
khenaidoob332f9b2020-01-16 16:25:26 -0500138 log *zp.SugaredLogger
139 parent *zp.Logger
140 packageName string
Scott Baker2c1c4822019-10-16 11:02:41 -0700141}
142
Rohan Agrawal0c62b5d2020-02-04 09:56:21 +0000143func logLevelToAtomicLevel(l LogLevel) zp.AtomicLevel {
Scott Baker2c1c4822019-10-16 11:02:41 -0700144 switch l {
145 case DebugLevel:
146 return zp.NewAtomicLevelAt(zc.DebugLevel)
147 case InfoLevel:
148 return zp.NewAtomicLevelAt(zc.InfoLevel)
149 case WarnLevel:
150 return zp.NewAtomicLevelAt(zc.WarnLevel)
151 case ErrorLevel:
152 return zp.NewAtomicLevelAt(zc.ErrorLevel)
Scott Baker2c1c4822019-10-16 11:02:41 -0700153 case FatalLevel:
154 return zp.NewAtomicLevelAt(zc.FatalLevel)
155 }
156 return zp.NewAtomicLevelAt(zc.ErrorLevel)
157}
158
Rohan Agrawal0c62b5d2020-02-04 09:56:21 +0000159func logLevelToLevel(l LogLevel) zc.Level {
Scott Baker2c1c4822019-10-16 11:02:41 -0700160 switch l {
161 case DebugLevel:
162 return zc.DebugLevel
163 case InfoLevel:
164 return zc.InfoLevel
165 case WarnLevel:
166 return zc.WarnLevel
167 case ErrorLevel:
168 return zc.ErrorLevel
Scott Baker2c1c4822019-10-16 11:02:41 -0700169 case FatalLevel:
170 return zc.FatalLevel
171 }
172 return zc.ErrorLevel
173}
174
Rohan Agrawal0c62b5d2020-02-04 09:56:21 +0000175func levelToLogLevel(l zc.Level) LogLevel {
Scott Baker2c1c4822019-10-16 11:02:41 -0700176 switch l {
177 case zc.DebugLevel:
178 return DebugLevel
179 case zc.InfoLevel:
180 return InfoLevel
181 case zc.WarnLevel:
182 return WarnLevel
183 case zc.ErrorLevel:
184 return ErrorLevel
Rohan Agrawal6a99a452020-01-14 07:58:25 +0000185 case zc.FatalLevel:
186 return FatalLevel
187 }
188 return ErrorLevel
189}
190
Rohan Agrawal0c62b5d2020-02-04 09:56:21 +0000191func StringToLogLevel(l string) (LogLevel, error) {
192 switch strings.ToUpper(l) {
Rohan Agrawal6a99a452020-01-14 07:58:25 +0000193 case "DEBUG":
Rohan Agrawal0c62b5d2020-02-04 09:56:21 +0000194 return DebugLevel, nil
Rohan Agrawal6a99a452020-01-14 07:58:25 +0000195 case "INFO":
Rohan Agrawal0c62b5d2020-02-04 09:56:21 +0000196 return InfoLevel, nil
Rohan Agrawal6a99a452020-01-14 07:58:25 +0000197 case "WARN":
Rohan Agrawal0c62b5d2020-02-04 09:56:21 +0000198 return WarnLevel, nil
Rohan Agrawal6a99a452020-01-14 07:58:25 +0000199 case "ERROR":
Rohan Agrawal0c62b5d2020-02-04 09:56:21 +0000200 return ErrorLevel, nil
Rohan Agrawal6a99a452020-01-14 07:58:25 +0000201 case "FATAL":
Rohan Agrawal0c62b5d2020-02-04 09:56:21 +0000202 return FatalLevel, nil
Scott Baker2c1c4822019-10-16 11:02:41 -0700203 }
Rohan Agrawal0c62b5d2020-02-04 09:56:21 +0000204 return 0, errors.New("Given LogLevel is invalid : " + l)
Scott Baker2c1c4822019-10-16 11:02:41 -0700205}
206
divyadesai8bf96862020-02-07 12:24:26 +0000207func LogLevelToString(l LogLevel) (string, error) {
208 switch l {
209 case DebugLevel:
210 return "DEBUG", nil
211 case InfoLevel:
212 return "INFO", nil
213 case WarnLevel:
214 return "WARN", nil
215 case ErrorLevel:
216 return "ERROR", nil
217 case FatalLevel:
218 return "FATAL", nil
219 }
220 return "", errors.New("Given LogLevel is invalid " + string(l))
221}
222
Rohan Agrawal0c62b5d2020-02-04 09:56:21 +0000223func getDefaultConfig(outputType string, level LogLevel, defaultFields Fields) zp.Config {
Scott Baker2c1c4822019-10-16 11:02:41 -0700224 return zp.Config{
Rohan Agrawal0c62b5d2020-02-04 09:56:21 +0000225 Level: logLevelToAtomicLevel(level),
Scott Baker2c1c4822019-10-16 11:02:41 -0700226 Encoding: outputType,
227 Development: true,
228 OutputPaths: []string{"stdout"},
229 ErrorOutputPaths: []string{"stderr"},
230 InitialFields: defaultFields,
231 EncoderConfig: zc.EncoderConfig{
232 LevelKey: "level",
233 MessageKey: "msg",
234 TimeKey: "ts",
Girish Kumarc9b0e712020-02-27 17:50:52 +0000235 CallerKey: "caller",
Scott Baker2c1c4822019-10-16 11:02:41 -0700236 StacktraceKey: "stacktrace",
237 LineEnding: zc.DefaultLineEnding,
238 EncodeLevel: zc.LowercaseLevelEncoder,
239 EncodeTime: zc.ISO8601TimeEncoder,
240 EncodeDuration: zc.SecondsDurationEncoder,
241 EncodeCaller: zc.ShortCallerEncoder,
242 },
243 }
244}
245
Rohan Agrawalee87e642020-04-14 10:22:18 +0000246func ConstructZapConfig(outputType string, level LogLevel, fields Fields) zp.Config {
247 return getDefaultConfig(outputType, level, fields)
248}
249
Scott Baker2c1c4822019-10-16 11:02:41 -0700250// SetLogger needs to be invoked before the logger API can be invoked. This function
251// initialize the default logger (zap's sugaredlogger)
Girish Kumar46d7c3a2020-05-18 12:06:33 +0000252func SetDefaultLogger(outputType string, level LogLevel, defaultFields Fields) (CLogger, error) {
Scott Baker2c1c4822019-10-16 11:02:41 -0700253 // Build a custom config using zap
254 cfg = getDefaultConfig(outputType, level, defaultFields)
255
Girish Kumarc9b0e712020-02-27 17:50:52 +0000256 l, err := cfg.Build(zp.AddCallerSkip(1))
Scott Baker2c1c4822019-10-16 11:02:41 -0700257 if err != nil {
258 return nil, err
259 }
260
Girish Kumar46d7c3a2020-05-18 12:06:33 +0000261 defaultLogger = &clogger{
Scott Baker2c1c4822019-10-16 11:02:41 -0700262 log: l.Sugar(),
263 parent: l,
264 }
265
266 return defaultLogger, nil
267}
268
269// AddPackage registers a package to the log map. Each package gets its own logger which allows
270// its config (loglevel) to be changed dynamically without interacting with the other packages.
271// outputType is JSON, level is the lowest level log to output with this logger and defaultFields is a map of
272// key-value pairs to always add to the output.
273// Note: AddPackage also returns a reference to the actual logger. If a calling package uses this reference directly
274//instead of using the publicly available functions in this log package then a number of functionalities will not
275// be available to it, notably log tracing with filename.functionname.linenumber annotation.
276//
277// pkgNames parameter should be used for testing only as this function detects the caller's package.
Girish Kumar46d7c3a2020-05-18 12:06:33 +0000278func RegisterPackage(outputType string, level LogLevel, defaultFields Fields, pkgNames ...string) (CLogger, error) {
Scott Baker2c1c4822019-10-16 11:02:41 -0700279 if cfgs == nil {
280 cfgs = make(map[string]zp.Config)
281 }
282 if loggers == nil {
Girish Kumar46d7c3a2020-05-18 12:06:33 +0000283 loggers = make(map[string]*clogger)
Scott Baker2c1c4822019-10-16 11:02:41 -0700284 }
285
286 var pkgName string
287 for _, name := range pkgNames {
288 pkgName = name
289 break
290 }
291 if pkgName == "" {
292 pkgName, _, _, _ = getCallerInfo()
293 }
294
295 if _, exist := loggers[pkgName]; exist {
296 return loggers[pkgName], nil
297 }
298
299 cfgs[pkgName] = getDefaultConfig(outputType, level, defaultFields)
300
Girish Kumarc9b0e712020-02-27 17:50:52 +0000301 l, err := cfgs[pkgName].Build(zp.AddCallerSkip(1))
Scott Baker2c1c4822019-10-16 11:02:41 -0700302 if err != nil {
303 return nil, err
304 }
305
Girish Kumar46d7c3a2020-05-18 12:06:33 +0000306 loggers[pkgName] = &clogger{
khenaidoob332f9b2020-01-16 16:25:26 -0500307 log: l.Sugar(),
308 parent: l,
309 packageName: pkgName,
Scott Baker2c1c4822019-10-16 11:02:41 -0700310 }
311 return loggers[pkgName], nil
312}
313
314//UpdateAllLoggers create new loggers for all registered pacakges with the defaultFields.
315func UpdateAllLoggers(defaultFields Fields) error {
316 for pkgName, cfg := range cfgs {
317 for k, v := range defaultFields {
318 if cfg.InitialFields == nil {
319 cfg.InitialFields = make(map[string]interface{})
320 }
321 cfg.InitialFields[k] = v
322 }
Girish Kumarc9b0e712020-02-27 17:50:52 +0000323 l, err := cfg.Build(zp.AddCallerSkip(1))
Scott Baker2c1c4822019-10-16 11:02:41 -0700324 if err != nil {
325 return err
326 }
327
Girish Kumarc9b0e712020-02-27 17:50:52 +0000328 // Update the existing zap logger instance
329 loggers[pkgName].log = l.Sugar()
330 loggers[pkgName].parent = l
Scott Baker2c1c4822019-10-16 11:02:41 -0700331 }
332 return nil
333}
334
335// Return a list of all packages that have individually-configured loggers
336func GetPackageNames() []string {
337 i := 0
338 keys := make([]string, len(loggers))
339 for k := range loggers {
340 keys[i] = k
341 i++
342 }
343 return keys
344}
345
Girish Kumarc9b0e712020-02-27 17:50:52 +0000346// UpdateLogger updates the logger associated with a caller's package with supplied defaultFields
347func UpdateLogger(defaultFields Fields) error {
Scott Baker2c1c4822019-10-16 11:02:41 -0700348 pkgName, _, _, _ := getCallerInfo()
349 if _, exist := loggers[pkgName]; !exist {
Girish Kumarc9b0e712020-02-27 17:50:52 +0000350 return fmt.Errorf("package-%s-not-registered", pkgName)
Scott Baker2c1c4822019-10-16 11:02:41 -0700351 }
352
353 // Build a new logger
354 if _, exist := cfgs[pkgName]; !exist {
Girish Kumarc9b0e712020-02-27 17:50:52 +0000355 return fmt.Errorf("config-%s-not-registered", pkgName)
Scott Baker2c1c4822019-10-16 11:02:41 -0700356 }
357
358 cfg := cfgs[pkgName]
359 for k, v := range defaultFields {
360 if cfg.InitialFields == nil {
361 cfg.InitialFields = make(map[string]interface{})
362 }
363 cfg.InitialFields[k] = v
364 }
Girish Kumarc9b0e712020-02-27 17:50:52 +0000365 l, err := cfg.Build(zp.AddCallerSkip(1))
Scott Baker2c1c4822019-10-16 11:02:41 -0700366 if err != nil {
Girish Kumarc9b0e712020-02-27 17:50:52 +0000367 return err
Scott Baker2c1c4822019-10-16 11:02:41 -0700368 }
369
Girish Kumarc9b0e712020-02-27 17:50:52 +0000370 // Update the existing zap logger instance
371 loggers[pkgName].log = l.Sugar()
372 loggers[pkgName].parent = l
373
374 return nil
Scott Baker2c1c4822019-10-16 11:02:41 -0700375}
376
Rohan Agrawal0c62b5d2020-02-04 09:56:21 +0000377func setLevel(cfg zp.Config, level LogLevel) {
Scott Baker2c1c4822019-10-16 11:02:41 -0700378 switch level {
379 case DebugLevel:
380 cfg.Level.SetLevel(zc.DebugLevel)
381 case InfoLevel:
382 cfg.Level.SetLevel(zc.InfoLevel)
383 case WarnLevel:
384 cfg.Level.SetLevel(zc.WarnLevel)
385 case ErrorLevel:
386 cfg.Level.SetLevel(zc.ErrorLevel)
Scott Baker2c1c4822019-10-16 11:02:41 -0700387 case FatalLevel:
388 cfg.Level.SetLevel(zc.FatalLevel)
389 default:
390 cfg.Level.SetLevel(zc.ErrorLevel)
391 }
392}
393
394//SetPackageLogLevel dynamically sets the log level of a given package to level. This is typically invoked at an
395// application level during debugging
Rohan Agrawal0c62b5d2020-02-04 09:56:21 +0000396func SetPackageLogLevel(packageName string, level LogLevel) {
Scott Baker2c1c4822019-10-16 11:02:41 -0700397 // Get proper config
398 if cfg, ok := cfgs[packageName]; ok {
399 setLevel(cfg, level)
400 }
401}
402
403//SetAllLogLevel sets the log level of all registered packages to level
Rohan Agrawal0c62b5d2020-02-04 09:56:21 +0000404func SetAllLogLevel(level LogLevel) {
Scott Baker2c1c4822019-10-16 11:02:41 -0700405 // Get proper config
406 for _, cfg := range cfgs {
407 setLevel(cfg, level)
408 }
409}
410
411//GetPackageLogLevel returns the current log level of a package.
Rohan Agrawal0c62b5d2020-02-04 09:56:21 +0000412func GetPackageLogLevel(packageName ...string) (LogLevel, error) {
Scott Baker2c1c4822019-10-16 11:02:41 -0700413 var name string
414 if len(packageName) == 1 {
415 name = packageName[0]
416 } else {
417 name, _, _, _ = getCallerInfo()
418 }
419 if cfg, ok := cfgs[name]; ok {
Rohan Agrawal0c62b5d2020-02-04 09:56:21 +0000420 return levelToLogLevel(cfg.Level.Level()), nil
Scott Baker2c1c4822019-10-16 11:02:41 -0700421 }
David K. Bainbridge7c75cac2020-02-19 08:53:46 -0800422 return 0, fmt.Errorf("unknown-package-%s", name)
Scott Baker2c1c4822019-10-16 11:02:41 -0700423}
424
425//GetDefaultLogLevel gets the log level used for packages that don't have specific loggers
Rohan Agrawal0c62b5d2020-02-04 09:56:21 +0000426func GetDefaultLogLevel() LogLevel {
427 return levelToLogLevel(cfg.Level.Level())
Scott Baker2c1c4822019-10-16 11:02:41 -0700428}
429
430//SetLogLevel sets the log level for the logger corresponding to the caller's package
Rohan Agrawal0c62b5d2020-02-04 09:56:21 +0000431func SetLogLevel(level LogLevel) error {
Scott Baker2c1c4822019-10-16 11:02:41 -0700432 pkgName, _, _, _ := getCallerInfo()
433 if _, exist := cfgs[pkgName]; !exist {
David K. Bainbridge7c75cac2020-02-19 08:53:46 -0800434 return fmt.Errorf("unregistered-package-%s", pkgName)
Scott Baker2c1c4822019-10-16 11:02:41 -0700435 }
436 cfg := cfgs[pkgName]
437 setLevel(cfg, level)
438 return nil
439}
440
441//SetDefaultLogLevel sets the log level used for packages that don't have specific loggers
Rohan Agrawal0c62b5d2020-02-04 09:56:21 +0000442func SetDefaultLogLevel(level LogLevel) {
Scott Baker2c1c4822019-10-16 11:02:41 -0700443 setLevel(cfg, level)
444}
445
446// CleanUp flushed any buffered log entries. Applications should take care to call
447// CleanUp before exiting.
448func CleanUp() error {
449 for _, logger := range loggers {
450 if logger != nil {
451 if logger.parent != nil {
452 if err := logger.parent.Sync(); err != nil {
453 return err
454 }
455 }
456 }
457 }
458 if defaultLogger != nil {
459 if defaultLogger.parent != nil {
460 if err := defaultLogger.parent.Sync(); err != nil {
461 return err
462 }
463 }
464 }
465 return nil
466}
467
468func getCallerInfo() (string, string, string, int) {
469 // Since the caller of a log function is one stack frame before (in terms of stack higher level) the log.go
470 // filename, then first look for the last log.go filename and then grab the caller info one level higher.
471 maxLevel := 3
472 skiplevel := 3 // Level with the most empirical success to see the last log.go stack frame.
473 pc := make([]uintptr, maxLevel)
474 n := runtime.Callers(skiplevel, pc)
475 packageName := ""
476 funcName := ""
477 fileName := ""
478 var line int
479 if n == 0 {
480 return packageName, fileName, funcName, line
481 }
482 frames := runtime.CallersFrames(pc[:n])
483 var frame runtime.Frame
484 var foundFrame runtime.Frame
485 more := true
486 for more {
487 frame, more = frames.Next()
488 _, fileName = path.Split(frame.File)
489 if fileName != "log.go" {
490 foundFrame = frame // First frame after log.go in the frame stack
491 break
492 }
493 }
494 parts := strings.Split(foundFrame.Function, ".")
495 pl := len(parts)
496 if pl >= 2 {
497 funcName = parts[pl-1]
498 if parts[pl-2][0] == '(' {
499 packageName = strings.Join(parts[0:pl-2], ".")
500 } else {
501 packageName = strings.Join(parts[0:pl-1], ".")
502 }
503 }
504
505 if strings.HasSuffix(packageName, ".init") {
506 packageName = strings.TrimSuffix(packageName, ".init")
507 }
508
509 if strings.HasSuffix(fileName, ".go") {
510 fileName = strings.TrimSuffix(fileName, ".go")
511 }
512
513 return packageName, fileName, funcName, foundFrame.Line
514}
515
Scott Baker2c1c4822019-10-16 11:02:41 -0700516// With returns a logger initialized with the key-value pairs
Girish Kumar46d7c3a2020-05-18 12:06:33 +0000517func (l clogger) With(keysAndValues Fields) CLogger {
518 return clogger{log: l.log.With(serializeMap(keysAndValues)...), parent: l.parent}
Scott Baker2c1c4822019-10-16 11:02:41 -0700519}
520
521// Debug logs a message at level Debug on the standard logger.
Girish Kumar46d7c3a2020-05-18 12:06:33 +0000522func (l clogger) Debug(ctx context.Context, args ...interface{}) {
Girish Kumar503cce62020-08-24 16:34:39 +0000523 l.log.With(GetGlobalLFM().ExtractContextAttributes(ctx)...).Debug(args...)
Scott Baker2c1c4822019-10-16 11:02:41 -0700524}
525
526// 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 +0000527func (l clogger) Debugln(ctx context.Context, args ...interface{}) {
Girish Kumar503cce62020-08-24 16:34:39 +0000528 l.log.With(GetGlobalLFM().ExtractContextAttributes(ctx)...).Debug(args...)
Scott Baker2c1c4822019-10-16 11:02:41 -0700529}
530
531// Debugw logs a message at level Debug on the standard logger.
Girish Kumar46d7c3a2020-05-18 12:06:33 +0000532func (l clogger) Debugf(ctx context.Context, format string, args ...interface{}) {
Girish Kumar503cce62020-08-24 16:34:39 +0000533 l.log.With(GetGlobalLFM().ExtractContextAttributes(ctx)...).Debugf(format, args...)
Scott Baker2c1c4822019-10-16 11:02:41 -0700534}
535
536// Debugw logs a message with some additional context. The variadic key-value
537// pairs are treated as they are in With.
Girish Kumar46d7c3a2020-05-18 12:06:33 +0000538func (l clogger) Debugw(ctx context.Context, msg string, keysAndValues Fields) {
khenaidoob3ec7d52020-04-29 16:52:08 -0400539 if l.V(DebugLevel) {
Girish Kumar503cce62020-08-24 16:34:39 +0000540 l.log.With(GetGlobalLFM().ExtractContextAttributes(ctx)...).Debugw(msg, serializeMap(keysAndValues)...)
khenaidoob3ec7d52020-04-29 16:52:08 -0400541 }
Scott Baker2c1c4822019-10-16 11:02:41 -0700542}
543
544// Info logs a message at level Info on the standard logger.
Girish Kumar46d7c3a2020-05-18 12:06:33 +0000545func (l clogger) Info(ctx context.Context, args ...interface{}) {
Girish Kumar503cce62020-08-24 16:34:39 +0000546 l.log.With(GetGlobalLFM().ExtractContextAttributes(ctx)...).Info(args...)
Scott Baker2c1c4822019-10-16 11:02:41 -0700547}
548
549// 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 +0000550func (l clogger) Infoln(ctx context.Context, args ...interface{}) {
Girish Kumar503cce62020-08-24 16:34:39 +0000551 l.log.With(GetGlobalLFM().ExtractContextAttributes(ctx)...).Info(args...)
Scott Baker2c1c4822019-10-16 11:02:41 -0700552 //msg := fmt.Sprintln(args...)
553 //l.sourced().Info(msg[:len(msg)-1])
554}
555
556// Infof logs a message at level Info on the standard logger.
Girish Kumar46d7c3a2020-05-18 12:06:33 +0000557func (l clogger) Infof(ctx context.Context, format string, args ...interface{}) {
Girish Kumar503cce62020-08-24 16:34:39 +0000558 l.log.With(GetGlobalLFM().ExtractContextAttributes(ctx)...).Infof(format, args...)
Scott Baker2c1c4822019-10-16 11:02:41 -0700559}
560
561// Infow logs a message with some additional context. The variadic key-value
562// pairs are treated as they are in With.
Girish Kumar46d7c3a2020-05-18 12:06:33 +0000563func (l clogger) Infow(ctx context.Context, msg string, keysAndValues Fields) {
khenaidoob3ec7d52020-04-29 16:52:08 -0400564 if l.V(InfoLevel) {
Girish Kumar503cce62020-08-24 16:34:39 +0000565 l.log.With(GetGlobalLFM().ExtractContextAttributes(ctx)...).Infow(msg, serializeMap(keysAndValues)...)
khenaidoob3ec7d52020-04-29 16:52:08 -0400566 }
Scott Baker2c1c4822019-10-16 11:02:41 -0700567}
568
569// Warn logs a message at level Warn on the standard logger.
Girish Kumar46d7c3a2020-05-18 12:06:33 +0000570func (l clogger) Warn(ctx context.Context, args ...interface{}) {
Girish Kumar503cce62020-08-24 16:34:39 +0000571 l.log.With(GetGlobalLFM().ExtractContextAttributes(ctx)...).Warn(args...)
Scott Baker2c1c4822019-10-16 11:02:41 -0700572}
573
574// 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 +0000575func (l clogger) Warnln(ctx context.Context, args ...interface{}) {
Girish Kumar503cce62020-08-24 16:34:39 +0000576 l.log.With(GetGlobalLFM().ExtractContextAttributes(ctx)...).Warn(args...)
Scott Baker2c1c4822019-10-16 11:02:41 -0700577}
578
579// Warnf logs a message at level Warn on the standard logger.
Girish Kumar46d7c3a2020-05-18 12:06:33 +0000580func (l clogger) Warnf(ctx context.Context, format string, args ...interface{}) {
Girish Kumar503cce62020-08-24 16:34:39 +0000581 l.log.With(GetGlobalLFM().ExtractContextAttributes(ctx)...).Warnf(format, args...)
Scott Baker2c1c4822019-10-16 11:02:41 -0700582}
583
584// Warnw logs a message with some additional context. The variadic key-value
585// pairs are treated as they are in With.
Girish Kumar46d7c3a2020-05-18 12:06:33 +0000586func (l clogger) Warnw(ctx context.Context, msg string, keysAndValues Fields) {
khenaidoob3ec7d52020-04-29 16:52:08 -0400587 if l.V(WarnLevel) {
Girish Kumar503cce62020-08-24 16:34:39 +0000588 l.log.With(GetGlobalLFM().ExtractContextAttributes(ctx)...).Warnw(msg, serializeMap(keysAndValues)...)
khenaidoob3ec7d52020-04-29 16:52:08 -0400589 }
Scott Baker2c1c4822019-10-16 11:02:41 -0700590}
591
592// Error logs a message at level Error on the standard logger.
Girish Kumar46d7c3a2020-05-18 12:06:33 +0000593func (l clogger) Error(ctx context.Context, args ...interface{}) {
Girish Kumar503cce62020-08-24 16:34:39 +0000594 l.log.With(GetGlobalLFM().ExtractContextAttributes(ctx)...).Error(args...)
Scott Baker2c1c4822019-10-16 11:02:41 -0700595}
596
597// 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 +0000598func (l clogger) Errorln(ctx context.Context, args ...interface{}) {
Girish Kumar503cce62020-08-24 16:34:39 +0000599 l.log.With(GetGlobalLFM().ExtractContextAttributes(ctx)...).Error(args...)
Scott Baker2c1c4822019-10-16 11:02:41 -0700600}
601
602// Errorf logs a message at level Error on the standard logger.
Girish Kumar46d7c3a2020-05-18 12:06:33 +0000603func (l clogger) Errorf(ctx context.Context, format string, args ...interface{}) {
Girish Kumar503cce62020-08-24 16:34:39 +0000604 l.log.With(GetGlobalLFM().ExtractContextAttributes(ctx)...).Errorf(format, args...)
Scott Baker2c1c4822019-10-16 11:02:41 -0700605}
606
607// Errorw logs a message with some additional context. The variadic key-value
608// pairs are treated as they are in With.
Girish Kumar46d7c3a2020-05-18 12:06:33 +0000609func (l clogger) Errorw(ctx context.Context, msg string, keysAndValues Fields) {
khenaidoob3ec7d52020-04-29 16:52:08 -0400610 if l.V(ErrorLevel) {
Girish Kumar503cce62020-08-24 16:34:39 +0000611 l.log.With(GetGlobalLFM().ExtractContextAttributes(ctx)...).Errorw(msg, serializeMap(keysAndValues)...)
khenaidoob3ec7d52020-04-29 16:52:08 -0400612 }
Scott Baker2c1c4822019-10-16 11:02:41 -0700613}
614
615// Fatal logs a message at level Fatal on the standard logger.
Girish Kumar46d7c3a2020-05-18 12:06:33 +0000616func (l clogger) Fatal(ctx context.Context, args ...interface{}) {
Girish Kumar503cce62020-08-24 16:34:39 +0000617 l.log.With(GetGlobalLFM().ExtractContextAttributes(ctx)...).Fatal(args...)
Scott Baker2c1c4822019-10-16 11:02:41 -0700618}
619
620// 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 +0000621func (l clogger) Fatalln(ctx context.Context, args ...interface{}) {
Girish Kumar503cce62020-08-24 16:34:39 +0000622 l.log.With(GetGlobalLFM().ExtractContextAttributes(ctx)...).Fatal(args...)
Scott Baker2c1c4822019-10-16 11:02:41 -0700623}
624
625// Fatalf logs a message at level Fatal on the standard logger.
Girish Kumar46d7c3a2020-05-18 12:06:33 +0000626func (l clogger) Fatalf(ctx context.Context, format string, args ...interface{}) {
Girish Kumar503cce62020-08-24 16:34:39 +0000627 l.log.With(GetGlobalLFM().ExtractContextAttributes(ctx)...).Fatalf(format, args...)
Scott Baker2c1c4822019-10-16 11:02:41 -0700628}
629
630// Fatalw logs a message with some additional context. The variadic key-value
631// pairs are treated as they are in With.
Girish Kumar46d7c3a2020-05-18 12:06:33 +0000632func (l clogger) Fatalw(ctx context.Context, msg string, keysAndValues Fields) {
khenaidoob3ec7d52020-04-29 16:52:08 -0400633 if l.V(FatalLevel) {
Girish Kumar503cce62020-08-24 16:34:39 +0000634 l.log.With(GetGlobalLFM().ExtractContextAttributes(ctx)...).Fatalw(msg, serializeMap(keysAndValues)...)
khenaidoob3ec7d52020-04-29 16:52:08 -0400635 }
Scott Baker2c1c4822019-10-16 11:02:41 -0700636}
637
638// Warning logs a message at level Warn on the standard logger.
Girish Kumar46d7c3a2020-05-18 12:06:33 +0000639func (l clogger) Warning(ctx context.Context, args ...interface{}) {
Girish Kumar503cce62020-08-24 16:34:39 +0000640 l.log.With(GetGlobalLFM().ExtractContextAttributes(ctx)...).Warn(args...)
Scott Baker2c1c4822019-10-16 11:02:41 -0700641}
642
643// 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 +0000644func (l clogger) Warningln(ctx context.Context, args ...interface{}) {
Girish Kumar503cce62020-08-24 16:34:39 +0000645 l.log.With(GetGlobalLFM().ExtractContextAttributes(ctx)...).Warn(args...)
Scott Baker2c1c4822019-10-16 11:02:41 -0700646}
647
648// Warningf logs a message at level Warn on the standard logger.
Girish Kumar46d7c3a2020-05-18 12:06:33 +0000649func (l clogger) Warningf(ctx context.Context, format string, args ...interface{}) {
Girish Kumar503cce62020-08-24 16:34:39 +0000650 l.log.With(GetGlobalLFM().ExtractContextAttributes(ctx)...).Warnf(format, args...)
Scott Baker2c1c4822019-10-16 11:02:41 -0700651}
652
653// V reports whether verbosity level l is at least the requested verbose level.
Girish Kumar46d7c3a2020-05-18 12:06:33 +0000654func (l clogger) V(level LogLevel) bool {
Scott Bakerd7c25f42020-02-21 08:12:06 -0800655 return l.parent.Core().Enabled(logLevelToLevel(level))
Scott Baker2c1c4822019-10-16 11:02:41 -0700656}
657
khenaidoob332f9b2020-01-16 16:25:26 -0500658// GetLogLevel returns the current level of the logger
Girish Kumar46d7c3a2020-05-18 12:06:33 +0000659func (l clogger) GetLogLevel() LogLevel {
Rohan Agrawal0c62b5d2020-02-04 09:56:21 +0000660 return levelToLogLevel(cfgs[l.packageName].Level.Level())
khenaidoob332f9b2020-01-16 16:25:26 -0500661}