blob: 7b1a12379f5f11ab09233e70b4fb42c60cec0d08 [file] [log] [blame]
William Kurkianea869482019-04-09 15:16:11 -04001/*
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 Kumar935f7af2020-08-18 11:59:42 +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)
William Kurkianea869482019-04-09 15:16:11 -040024//
25// Using package-level logging (recommended approach). In the examples below, log refers to this log package.
William Kurkianea869482019-04-09 15:16:11 -040026//
Girish Kumar935f7af2020-08-18 11:59:42 +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.
William Kurkianea869482019-04-09 15:16:11 -040032//
Girish Kumar935f7af2020-08-18 11:59:42 +000033// var logger log.CLogger
34// func init() {
35// logger, err = log.RegisterPackage(log.JSON, log.ErrorLevel, log.Fields{"key1": "value1"})
36// }
William Kurkianea869482019-04-09 15:16:11 -040037//
Girish Kumar935f7af2020-08-18 11:59:42 +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:
William Kurkianea869482019-04-09 15:16:11 -040040//
Girish Kumar935f7af2020-08-18 11:59:42 +000041// logger.Infow("An example", mylog.Fields{"myStringOutput": "output", "myIntOutput": 2})
William Kurkianea869482019-04-09 15:16:11 -040042//
Girish Kumar935f7af2020-08-18 11:59:42 +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
William Kurkianea869482019-04-09 15:16:11 -040050
51package log
52
53import (
Girish Gowdra631ef3d2020-06-15 10:45:52 -070054 "context"
William Kurkianea869482019-04-09 15:16:11 -040055 "errors"
56 "fmt"
William Kurkianea869482019-04-09 15:16:11 -040057 "path"
58 "runtime"
59 "strings"
David K. Bainbridge2f2658d2021-04-09 16:13:57 +000060
61 zp "go.uber.org/zap"
62 zc "go.uber.org/zap/zapcore"
William Kurkianea869482019-04-09 15:16:11 -040063)
64
Rohan Agrawal02f784d2020-02-14 09:34:02 +000065type LogLevel int8
66
William Kurkianea869482019-04-09 15:16:11 -040067const (
68 // DebugLevel logs a message at debug level
Rohan Agrawal02f784d2020-02-14 09:34:02 +000069 DebugLevel = LogLevel(iota)
William Kurkianea869482019-04-09 15:16:11 -040070 // 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
William Kurkianea869482019-04-09 15:16:11 -040076 // 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 Gowdra631ef3d2020-06-15 10:45:52 -070086// Context Aware Logger represents an abstract logging interface. Any logging implementation used
William Kurkianea869482019-04-09 15:16:11 -040087// will need to abide by this interface
Girish Gowdra631ef3d2020-06-15 10:45:52 -070088type CLogger interface {
89 Debug(context.Context, ...interface{})
90 Debugln(context.Context, ...interface{})
91 Debugf(context.Context, string, ...interface{})
92 Debugw(context.Context, string, Fields)
William Kurkianea869482019-04-09 15:16:11 -040093
Girish Gowdra631ef3d2020-06-15 10:45:52 -070094 Info(context.Context, ...interface{})
95 Infoln(context.Context, ...interface{})
96 Infof(context.Context, string, ...interface{})
97 Infow(context.Context, string, Fields)
William Kurkianea869482019-04-09 15:16:11 -040098
Girish Gowdra631ef3d2020-06-15 10:45:52 -070099 Warn(context.Context, ...interface{})
100 Warnln(context.Context, ...interface{})
101 Warnf(context.Context, string, ...interface{})
102 Warnw(context.Context, string, Fields)
William Kurkianea869482019-04-09 15:16:11 -0400103
Girish Gowdra631ef3d2020-06-15 10:45:52 -0700104 Error(context.Context, ...interface{})
105 Errorln(context.Context, ...interface{})
106 Errorf(context.Context, string, ...interface{})
107 Errorw(context.Context, string, Fields)
William Kurkianea869482019-04-09 15:16:11 -0400108
Girish Gowdra631ef3d2020-06-15 10:45:52 -0700109 Fatal(context.Context, ...interface{})
110 Fatalln(context.Context, ...interface{})
111 Fatalf(context.Context, string, ...interface{})
112 Fatalw(context.Context, string, Fields)
William Kurkianea869482019-04-09 15:16:11 -0400113
Girish Gowdra631ef3d2020-06-15 10:45:52 -0700114 With(Fields) CLogger
William Kurkianea869482019-04-09 15:16:11 -0400115
116 // The following are added to be able to use this logger as a gRPC LoggerV2 if needed
117 //
Girish Gowdra631ef3d2020-06-15 10:45:52 -0700118 Warning(context.Context, ...interface{})
119 Warningln(context.Context, ...interface{})
120 Warningf(context.Context, string, ...interface{})
William Kurkianea869482019-04-09 15:16:11 -0400121
122 // V reports whether verbosity level l is at least the requested verbose level.
Rohan Agrawal02f784d2020-02-14 09:34:02 +0000123 V(l LogLevel) bool
Esin Karamanccb714b2019-11-29 15:02:06 +0000124
125 //Returns the log level of this specific logger
Rohan Agrawal02f784d2020-02-14 09:34:02 +0000126 GetLogLevel() LogLevel
William Kurkianea869482019-04-09 15:16:11 -0400127}
128
129// Fields is used as key-value pairs for structured logging
130type Fields map[string]interface{}
131
Girish Gowdra631ef3d2020-06-15 10:45:52 -0700132var defaultLogger *clogger
William Kurkianea869482019-04-09 15:16:11 -0400133var cfg zp.Config
134
Girish Gowdra631ef3d2020-06-15 10:45:52 -0700135var loggers map[string]*clogger
William Kurkianea869482019-04-09 15:16:11 -0400136var cfgs map[string]zp.Config
137
Girish Gowdra631ef3d2020-06-15 10:45:52 -0700138type clogger struct {
Esin Karamanccb714b2019-11-29 15:02:06 +0000139 log *zp.SugaredLogger
140 parent *zp.Logger
141 packageName string
William Kurkianea869482019-04-09 15:16:11 -0400142}
143
Rohan Agrawal02f784d2020-02-14 09:34:02 +0000144func logLevelToAtomicLevel(l LogLevel) zp.AtomicLevel {
William Kurkianea869482019-04-09 15:16:11 -0400145 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)
William Kurkianea869482019-04-09 15:16:11 -0400154 case FatalLevel:
155 return zp.NewAtomicLevelAt(zc.FatalLevel)
156 }
157 return zp.NewAtomicLevelAt(zc.ErrorLevel)
158}
159
Rohan Agrawal02f784d2020-02-14 09:34:02 +0000160func logLevelToLevel(l LogLevel) zc.Level {
William Kurkianea869482019-04-09 15:16:11 -0400161 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
William Kurkianea869482019-04-09 15:16:11 -0400170 case FatalLevel:
171 return zc.FatalLevel
172 }
173 return zc.ErrorLevel
174}
175
Rohan Agrawal02f784d2020-02-14 09:34:02 +0000176func levelToLogLevel(l zc.Level) LogLevel {
William Kurkianea869482019-04-09 15:16:11 -0400177 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
Esin Karamanccb714b2019-11-29 15:02:06 +0000186 case zc.FatalLevel:
187 return FatalLevel
188 }
189 return ErrorLevel
190}
191
Rohan Agrawal02f784d2020-02-14 09:34:02 +0000192func StringToLogLevel(l string) (LogLevel, error) {
193 switch strings.ToUpper(l) {
Esin Karamanccb714b2019-11-29 15:02:06 +0000194 case "DEBUG":
Rohan Agrawal02f784d2020-02-14 09:34:02 +0000195 return DebugLevel, nil
Esin Karamanccb714b2019-11-29 15:02:06 +0000196 case "INFO":
Rohan Agrawal02f784d2020-02-14 09:34:02 +0000197 return InfoLevel, nil
Esin Karamanccb714b2019-11-29 15:02:06 +0000198 case "WARN":
Rohan Agrawal02f784d2020-02-14 09:34:02 +0000199 return WarnLevel, nil
Esin Karamanccb714b2019-11-29 15:02:06 +0000200 case "ERROR":
Rohan Agrawal02f784d2020-02-14 09:34:02 +0000201 return ErrorLevel, nil
Esin Karamanccb714b2019-11-29 15:02:06 +0000202 case "FATAL":
Rohan Agrawal02f784d2020-02-14 09:34:02 +0000203 return FatalLevel, nil
William Kurkianea869482019-04-09 15:16:11 -0400204 }
Rohan Agrawal02f784d2020-02-14 09:34:02 +0000205 return 0, errors.New("Given LogLevel is invalid : " + l)
William Kurkianea869482019-04-09 15:16:11 -0400206}
207
Scott Bakere701b862020-02-20 16:19:16 -0800208func 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. Bainbridge2f2658d2021-04-09 16:13:57 +0000221 return "", fmt.Errorf("Given LogLevel is invalid %d", l)
Scott Bakere701b862020-02-20 16:19:16 -0800222}
223
Rohan Agrawal02f784d2020-02-14 09:34:02 +0000224func getDefaultConfig(outputType string, level LogLevel, defaultFields Fields) zp.Config {
William Kurkianea869482019-04-09 15:16:11 -0400225 return zp.Config{
Rohan Agrawal02f784d2020-02-14 09:34:02 +0000226 Level: logLevelToAtomicLevel(level),
William Kurkianea869482019-04-09 15:16:11 -0400227 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",
divyadesaid26f6b12020-03-19 06:30:28 +0000236 CallerKey: "caller",
William Kurkianea869482019-04-09 15:16:11 -0400237 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
Scott Bakered4a8e72020-04-17 11:10:20 -0700247func ConstructZapConfig(outputType string, level LogLevel, fields Fields) zp.Config {
248 return getDefaultConfig(outputType, level, fields)
249}
250
William Kurkianea869482019-04-09 15:16:11 -0400251// SetLogger needs to be invoked before the logger API can be invoked. This function
252// initialize the default logger (zap's sugaredlogger)
Girish Gowdra631ef3d2020-06-15 10:45:52 -0700253func SetDefaultLogger(outputType string, level LogLevel, defaultFields Fields) (CLogger, error) {
William Kurkianea869482019-04-09 15:16:11 -0400254 // Build a custom config using zap
255 cfg = getDefaultConfig(outputType, level, defaultFields)
256
divyadesaid26f6b12020-03-19 06:30:28 +0000257 l, err := cfg.Build(zp.AddCallerSkip(1))
William Kurkianea869482019-04-09 15:16:11 -0400258 if err != nil {
259 return nil, err
260 }
261
Girish Gowdra631ef3d2020-06-15 10:45:52 -0700262 defaultLogger = &clogger{
William Kurkianea869482019-04-09 15:16:11 -0400263 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
275//instead of using the publicly available functions in this log package then a number of functionalities will not
276// 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 Gowdra631ef3d2020-06-15 10:45:52 -0700279func RegisterPackage(outputType string, level LogLevel, defaultFields Fields, pkgNames ...string) (CLogger, error) {
William Kurkianea869482019-04-09 15:16:11 -0400280 if cfgs == nil {
281 cfgs = make(map[string]zp.Config)
282 }
283 if loggers == nil {
Girish Gowdra631ef3d2020-06-15 10:45:52 -0700284 loggers = make(map[string]*clogger)
William Kurkianea869482019-04-09 15:16:11 -0400285 }
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
divyadesaid26f6b12020-03-19 06:30:28 +0000302 l, err := cfgs[pkgName].Build(zp.AddCallerSkip(1))
William Kurkianea869482019-04-09 15:16:11 -0400303 if err != nil {
304 return nil, err
305 }
306
Girish Gowdra631ef3d2020-06-15 10:45:52 -0700307 loggers[pkgName] = &clogger{
Esin Karamanccb714b2019-11-29 15:02:06 +0000308 log: l.Sugar(),
309 parent: l,
310 packageName: pkgName,
William Kurkianea869482019-04-09 15:16:11 -0400311 }
312 return loggers[pkgName], nil
313}
314
315//UpdateAllLoggers create new loggers for all registered pacakges with the defaultFields.
316func 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 }
divyadesaid26f6b12020-03-19 06:30:28 +0000324 l, err := cfg.Build(zp.AddCallerSkip(1))
William Kurkianea869482019-04-09 15:16:11 -0400325 if err != nil {
326 return err
327 }
328
divyadesaid26f6b12020-03-19 06:30:28 +0000329 // Update the existing zap logger instance
330 loggers[pkgName].log = l.Sugar()
331 loggers[pkgName].parent = l
William Kurkianea869482019-04-09 15:16:11 -0400332 }
333 return nil
334}
335
kdarapub26b4502019-10-05 03:02:33 +0530336// 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
divyadesaid26f6b12020-03-19 06:30:28 +0000347// UpdateLogger updates the logger associated with a caller's package with supplied defaultFields
348func UpdateLogger(defaultFields Fields) error {
William Kurkianea869482019-04-09 15:16:11 -0400349 pkgName, _, _, _ := getCallerInfo()
350 if _, exist := loggers[pkgName]; !exist {
divyadesaid26f6b12020-03-19 06:30:28 +0000351 return fmt.Errorf("package-%s-not-registered", pkgName)
William Kurkianea869482019-04-09 15:16:11 -0400352 }
353
354 // Build a new logger
355 if _, exist := cfgs[pkgName]; !exist {
divyadesaid26f6b12020-03-19 06:30:28 +0000356 return fmt.Errorf("config-%s-not-registered", pkgName)
William Kurkianea869482019-04-09 15:16:11 -0400357 }
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 }
divyadesaid26f6b12020-03-19 06:30:28 +0000366 l, err := cfg.Build(zp.AddCallerSkip(1))
William Kurkianea869482019-04-09 15:16:11 -0400367 if err != nil {
divyadesaid26f6b12020-03-19 06:30:28 +0000368 return err
William Kurkianea869482019-04-09 15:16:11 -0400369 }
370
divyadesaid26f6b12020-03-19 06:30:28 +0000371 // Update the existing zap logger instance
372 loggers[pkgName].log = l.Sugar()
373 loggers[pkgName].parent = l
374
375 return nil
William Kurkianea869482019-04-09 15:16:11 -0400376}
377
Rohan Agrawal02f784d2020-02-14 09:34:02 +0000378func setLevel(cfg zp.Config, level LogLevel) {
William Kurkianea869482019-04-09 15:16:11 -0400379 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)
William Kurkianea869482019-04-09 15:16:11 -0400388 case FatalLevel:
389 cfg.Level.SetLevel(zc.FatalLevel)
390 default:
391 cfg.Level.SetLevel(zc.ErrorLevel)
392 }
393}
394
395//SetPackageLogLevel dynamically sets the log level of a given package to level. This is typically invoked at an
396// application level during debugging
Rohan Agrawal02f784d2020-02-14 09:34:02 +0000397func SetPackageLogLevel(packageName string, level LogLevel) {
William Kurkianea869482019-04-09 15:16:11 -0400398 // Get proper config
399 if cfg, ok := cfgs[packageName]; ok {
400 setLevel(cfg, level)
401 }
402}
403
404//SetAllLogLevel sets the log level of all registered packages to level
Rohan Agrawal02f784d2020-02-14 09:34:02 +0000405func SetAllLogLevel(level LogLevel) {
William Kurkianea869482019-04-09 15:16:11 -0400406 // Get proper config
407 for _, cfg := range cfgs {
408 setLevel(cfg, level)
409 }
410}
411
412//GetPackageLogLevel returns the current log level of a package.
Rohan Agrawal02f784d2020-02-14 09:34:02 +0000413func GetPackageLogLevel(packageName ...string) (LogLevel, error) {
Matt Jeanneretcab955f2019-04-10 15:45:57 -0400414 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 Agrawal02f784d2020-02-14 09:34:02 +0000421 return levelToLogLevel(cfg.Level.Level()), nil
William Kurkianea869482019-04-09 15:16:11 -0400422 }
Rohan Agrawal02f784d2020-02-14 09:34:02 +0000423 return 0, fmt.Errorf("unknown-package-%s", name)
William Kurkianea869482019-04-09 15:16:11 -0400424}
425
kdarapub26b4502019-10-05 03:02:33 +0530426//GetDefaultLogLevel gets the log level used for packages that don't have specific loggers
Rohan Agrawal02f784d2020-02-14 09:34:02 +0000427func GetDefaultLogLevel() LogLevel {
428 return levelToLogLevel(cfg.Level.Level())
kdarapub26b4502019-10-05 03:02:33 +0530429}
430
William Kurkianea869482019-04-09 15:16:11 -0400431//SetLogLevel sets the log level for the logger corresponding to the caller's package
Rohan Agrawal02f784d2020-02-14 09:34:02 +0000432func SetLogLevel(level LogLevel) error {
William Kurkianea869482019-04-09 15:16:11 -0400433 pkgName, _, _, _ := getCallerInfo()
434 if _, exist := cfgs[pkgName]; !exist {
Rohan Agrawal02f784d2020-02-14 09:34:02 +0000435 return fmt.Errorf("unregistered-package-%s", pkgName)
William Kurkianea869482019-04-09 15:16:11 -0400436 }
437 cfg := cfgs[pkgName]
438 setLevel(cfg, level)
439 return nil
440}
441
kdarapub26b4502019-10-05 03:02:33 +0530442//SetDefaultLogLevel sets the log level used for packages that don't have specific loggers
Rohan Agrawal02f784d2020-02-14 09:34:02 +0000443func SetDefaultLogLevel(level LogLevel) {
kdarapub26b4502019-10-05 03:02:33 +0530444 setLevel(cfg, level)
445}
446
William Kurkianea869482019-04-09 15:16:11 -0400447// 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
William Kurkianea869482019-04-09 15:16:11 -0400517// With returns a logger initialized with the key-value pairs
Girish Gowdra631ef3d2020-06-15 10:45:52 -0700518func (l clogger) With(keysAndValues Fields) CLogger {
519 return clogger{log: l.log.With(serializeMap(keysAndValues)...), parent: l.parent}
William Kurkianea869482019-04-09 15:16:11 -0400520}
521
522// Debug logs a message at level Debug on the standard logger.
Girish Gowdra631ef3d2020-06-15 10:45:52 -0700523func (l clogger) Debug(ctx context.Context, args ...interface{}) {
Girish Kumar935f7af2020-08-18 11:59:42 +0000524 l.log.With(GetGlobalLFM().ExtractContextAttributes(ctx)...).Debug(args...)
William Kurkianea869482019-04-09 15:16:11 -0400525}
526
527// Debugln logs a message at level Debug on the standard logger with a line feed. Default in any case.
Girish Gowdra631ef3d2020-06-15 10:45:52 -0700528func (l clogger) Debugln(ctx context.Context, args ...interface{}) {
Girish Kumar935f7af2020-08-18 11:59:42 +0000529 l.log.With(GetGlobalLFM().ExtractContextAttributes(ctx)...).Debug(args...)
William Kurkianea869482019-04-09 15:16:11 -0400530}
531
532// Debugw logs a message at level Debug on the standard logger.
Girish Gowdra631ef3d2020-06-15 10:45:52 -0700533func (l clogger) Debugf(ctx context.Context, format string, args ...interface{}) {
Girish Kumar935f7af2020-08-18 11:59:42 +0000534 l.log.With(GetGlobalLFM().ExtractContextAttributes(ctx)...).Debugf(format, args...)
William Kurkianea869482019-04-09 15:16:11 -0400535}
536
537// Debugw logs a message with some additional context. The variadic key-value
538// pairs are treated as they are in With.
Girish Gowdra631ef3d2020-06-15 10:45:52 -0700539func (l clogger) Debugw(ctx context.Context, msg string, keysAndValues Fields) {
Neha Sharmacc656962020-04-14 14:26:11 +0000540 if l.V(DebugLevel) {
Girish Kumar935f7af2020-08-18 11:59:42 +0000541 l.log.With(GetGlobalLFM().ExtractContextAttributes(ctx)...).Debugw(msg, serializeMap(keysAndValues)...)
Neha Sharmacc656962020-04-14 14:26:11 +0000542 }
William Kurkianea869482019-04-09 15:16:11 -0400543}
544
545// Info logs a message at level Info on the standard logger.
Girish Gowdra631ef3d2020-06-15 10:45:52 -0700546func (l clogger) Info(ctx context.Context, args ...interface{}) {
Girish Kumar935f7af2020-08-18 11:59:42 +0000547 l.log.With(GetGlobalLFM().ExtractContextAttributes(ctx)...).Info(args...)
William Kurkianea869482019-04-09 15:16:11 -0400548}
549
550// Infoln logs a message at level Info on the standard logger with a line feed. Default in any case.
Girish Gowdra631ef3d2020-06-15 10:45:52 -0700551func (l clogger) Infoln(ctx context.Context, args ...interface{}) {
Girish Kumar935f7af2020-08-18 11:59:42 +0000552 l.log.With(GetGlobalLFM().ExtractContextAttributes(ctx)...).Info(args...)
William Kurkianea869482019-04-09 15:16:11 -0400553 //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 Gowdra631ef3d2020-06-15 10:45:52 -0700558func (l clogger) Infof(ctx context.Context, format string, args ...interface{}) {
Girish Kumar935f7af2020-08-18 11:59:42 +0000559 l.log.With(GetGlobalLFM().ExtractContextAttributes(ctx)...).Infof(format, args...)
William Kurkianea869482019-04-09 15:16:11 -0400560}
561
562// Infow logs a message with some additional context. The variadic key-value
563// pairs are treated as they are in With.
Girish Gowdra631ef3d2020-06-15 10:45:52 -0700564func (l clogger) Infow(ctx context.Context, msg string, keysAndValues Fields) {
Neha Sharmacc656962020-04-14 14:26:11 +0000565 if l.V(InfoLevel) {
Girish Kumar935f7af2020-08-18 11:59:42 +0000566 l.log.With(GetGlobalLFM().ExtractContextAttributes(ctx)...).Infow(msg, serializeMap(keysAndValues)...)
Neha Sharmacc656962020-04-14 14:26:11 +0000567 }
William Kurkianea869482019-04-09 15:16:11 -0400568}
569
570// Warn logs a message at level Warn on the standard logger.
Girish Gowdra631ef3d2020-06-15 10:45:52 -0700571func (l clogger) Warn(ctx context.Context, args ...interface{}) {
Girish Kumar935f7af2020-08-18 11:59:42 +0000572 l.log.With(GetGlobalLFM().ExtractContextAttributes(ctx)...).Warn(args...)
William Kurkianea869482019-04-09 15:16:11 -0400573}
574
575// Warnln logs a message at level Warn on the standard logger with a line feed. Default in any case.
Girish Gowdra631ef3d2020-06-15 10:45:52 -0700576func (l clogger) Warnln(ctx context.Context, args ...interface{}) {
Girish Kumar935f7af2020-08-18 11:59:42 +0000577 l.log.With(GetGlobalLFM().ExtractContextAttributes(ctx)...).Warn(args...)
William Kurkianea869482019-04-09 15:16:11 -0400578}
579
580// Warnf logs a message at level Warn on the standard logger.
Girish Gowdra631ef3d2020-06-15 10:45:52 -0700581func (l clogger) Warnf(ctx context.Context, format string, args ...interface{}) {
Girish Kumar935f7af2020-08-18 11:59:42 +0000582 l.log.With(GetGlobalLFM().ExtractContextAttributes(ctx)...).Warnf(format, args...)
William Kurkianea869482019-04-09 15:16:11 -0400583}
584
585// Warnw logs a message with some additional context. The variadic key-value
586// pairs are treated as they are in With.
Girish Gowdra631ef3d2020-06-15 10:45:52 -0700587func (l clogger) Warnw(ctx context.Context, msg string, keysAndValues Fields) {
Neha Sharmacc656962020-04-14 14:26:11 +0000588 if l.V(WarnLevel) {
Girish Kumar935f7af2020-08-18 11:59:42 +0000589 l.log.With(GetGlobalLFM().ExtractContextAttributes(ctx)...).Warnw(msg, serializeMap(keysAndValues)...)
Neha Sharmacc656962020-04-14 14:26:11 +0000590 }
William Kurkianea869482019-04-09 15:16:11 -0400591}
592
593// Error logs a message at level Error on the standard logger.
Girish Gowdra631ef3d2020-06-15 10:45:52 -0700594func (l clogger) Error(ctx context.Context, args ...interface{}) {
Girish Kumar935f7af2020-08-18 11:59:42 +0000595 l.log.With(GetGlobalLFM().ExtractContextAttributes(ctx)...).Error(args...)
William Kurkianea869482019-04-09 15:16:11 -0400596}
597
598// Errorln logs a message at level Error on the standard logger with a line feed. Default in any case.
Girish Gowdra631ef3d2020-06-15 10:45:52 -0700599func (l clogger) Errorln(ctx context.Context, args ...interface{}) {
Girish Kumar935f7af2020-08-18 11:59:42 +0000600 l.log.With(GetGlobalLFM().ExtractContextAttributes(ctx)...).Error(args...)
William Kurkianea869482019-04-09 15:16:11 -0400601}
602
603// Errorf logs a message at level Error on the standard logger.
Girish Gowdra631ef3d2020-06-15 10:45:52 -0700604func (l clogger) Errorf(ctx context.Context, format string, args ...interface{}) {
Girish Kumar935f7af2020-08-18 11:59:42 +0000605 l.log.With(GetGlobalLFM().ExtractContextAttributes(ctx)...).Errorf(format, args...)
William Kurkianea869482019-04-09 15:16:11 -0400606}
607
608// Errorw logs a message with some additional context. The variadic key-value
609// pairs are treated as they are in With.
Girish Gowdra631ef3d2020-06-15 10:45:52 -0700610func (l clogger) Errorw(ctx context.Context, msg string, keysAndValues Fields) {
Neha Sharmacc656962020-04-14 14:26:11 +0000611 if l.V(ErrorLevel) {
Girish Kumar935f7af2020-08-18 11:59:42 +0000612 l.log.With(GetGlobalLFM().ExtractContextAttributes(ctx)...).Errorw(msg, serializeMap(keysAndValues)...)
Neha Sharmacc656962020-04-14 14:26:11 +0000613 }
William Kurkianea869482019-04-09 15:16:11 -0400614}
615
616// Fatal logs a message at level Fatal on the standard logger.
Girish Gowdra631ef3d2020-06-15 10:45:52 -0700617func (l clogger) Fatal(ctx context.Context, args ...interface{}) {
Girish Kumar935f7af2020-08-18 11:59:42 +0000618 l.log.With(GetGlobalLFM().ExtractContextAttributes(ctx)...).Fatal(args...)
William Kurkianea869482019-04-09 15:16:11 -0400619}
620
621// Fatalln logs a message at level Fatal on the standard logger with a line feed. Default in any case.
Girish Gowdra631ef3d2020-06-15 10:45:52 -0700622func (l clogger) Fatalln(ctx context.Context, args ...interface{}) {
Girish Kumar935f7af2020-08-18 11:59:42 +0000623 l.log.With(GetGlobalLFM().ExtractContextAttributes(ctx)...).Fatal(args...)
William Kurkianea869482019-04-09 15:16:11 -0400624}
625
626// Fatalf logs a message at level Fatal on the standard logger.
Girish Gowdra631ef3d2020-06-15 10:45:52 -0700627func (l clogger) Fatalf(ctx context.Context, format string, args ...interface{}) {
Girish Kumar935f7af2020-08-18 11:59:42 +0000628 l.log.With(GetGlobalLFM().ExtractContextAttributes(ctx)...).Fatalf(format, args...)
William Kurkianea869482019-04-09 15:16:11 -0400629}
630
631// Fatalw logs a message with some additional context. The variadic key-value
632// pairs are treated as they are in With.
Girish Gowdra631ef3d2020-06-15 10:45:52 -0700633func (l clogger) Fatalw(ctx context.Context, msg string, keysAndValues Fields) {
Neha Sharmacc656962020-04-14 14:26:11 +0000634 if l.V(FatalLevel) {
Girish Kumar935f7af2020-08-18 11:59:42 +0000635 l.log.With(GetGlobalLFM().ExtractContextAttributes(ctx)...).Fatalw(msg, serializeMap(keysAndValues)...)
Neha Sharmacc656962020-04-14 14:26:11 +0000636 }
William Kurkianea869482019-04-09 15:16:11 -0400637}
638
639// Warning logs a message at level Warn on the standard logger.
Girish Gowdra631ef3d2020-06-15 10:45:52 -0700640func (l clogger) Warning(ctx context.Context, args ...interface{}) {
Girish Kumar935f7af2020-08-18 11:59:42 +0000641 l.log.With(GetGlobalLFM().ExtractContextAttributes(ctx)...).Warn(args...)
William Kurkianea869482019-04-09 15:16:11 -0400642}
643
644// Warningln logs a message at level Warn on the standard logger with a line feed. Default in any case.
Girish Gowdra631ef3d2020-06-15 10:45:52 -0700645func (l clogger) Warningln(ctx context.Context, args ...interface{}) {
Girish Kumar935f7af2020-08-18 11:59:42 +0000646 l.log.With(GetGlobalLFM().ExtractContextAttributes(ctx)...).Warn(args...)
William Kurkianea869482019-04-09 15:16:11 -0400647}
648
649// Warningf logs a message at level Warn on the standard logger.
Girish Gowdra631ef3d2020-06-15 10:45:52 -0700650func (l clogger) Warningf(ctx context.Context, format string, args ...interface{}) {
Girish Kumar935f7af2020-08-18 11:59:42 +0000651 l.log.With(GetGlobalLFM().ExtractContextAttributes(ctx)...).Warnf(format, args...)
William Kurkianea869482019-04-09 15:16:11 -0400652}
653
654// V reports whether verbosity level l is at least the requested verbose level.
Girish Gowdra631ef3d2020-06-15 10:45:52 -0700655func (l clogger) V(level LogLevel) bool {
Rohan Agrawal02f784d2020-02-14 09:34:02 +0000656 return l.parent.Core().Enabled(logLevelToLevel(level))
William Kurkianea869482019-04-09 15:16:11 -0400657}
658
Esin Karamanccb714b2019-11-29 15:02:06 +0000659// GetLogLevel returns the current level of the logger
Girish Gowdra631ef3d2020-06-15 10:45:52 -0700660func (l clogger) GetLogLevel() LogLevel {
Rohan Agrawal02f784d2020-02-14 09:34:02 +0000661 return levelToLogLevel(cfgs[l.packageName].Level.Level())
Esin Karamanccb714b2019-11-29 15:02:06 +0000662}