blob: 7b1a12379f5f11ab09233e70b4fb42c60cec0d08 [file] [log] [blame]
Don Newton7577f072020-01-06 12:41:11 -05001/*
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 Kumarcd402012020-08-18 12:17:38 +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)
Don Newton7577f072020-01-06 12:41:11 -050024//
25// Using package-level logging (recommended approach). In the examples below, log refers to this log package.
Don Newton7577f072020-01-06 12:41:11 -050026//
Girish Kumarcd402012020-08-18 12:17:38 +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.
Don Newton7577f072020-01-06 12:41:11 -050032//
Girish Kumarcd402012020-08-18 12:17:38 +000033// var logger log.CLogger
34// func init() {
35// logger, err = log.RegisterPackage(log.JSON, log.ErrorLevel, log.Fields{"key1": "value1"})
36// }
Don Newton7577f072020-01-06 12:41:11 -050037//
Girish Kumarcd402012020-08-18 12:17:38 +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:
Don Newton7577f072020-01-06 12:41:11 -050040//
Girish Kumarcd402012020-08-18 12:17:38 +000041// logger.Infow("An example", mylog.Fields{"myStringOutput": "output", "myIntOutput": 2})
Don Newton7577f072020-01-06 12:41:11 -050042//
Girish Kumarcd402012020-08-18 12:17:38 +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
Don Newton7577f072020-01-06 12:41:11 -050050
51package log
52
53import (
Rohan Agrawalc32d9932020-06-15 11:01:47 +000054 "context"
Don Newton7577f072020-01-06 12:41:11 -050055 "errors"
56 "fmt"
Don Newton7577f072020-01-06 12:41:11 -050057 "path"
58 "runtime"
59 "strings"
David K. Bainbridge595b6702021-04-09 16:10:58 +000060
61 zp "go.uber.org/zap"
62 zc "go.uber.org/zap/zapcore"
Don Newton7577f072020-01-06 12:41:11 -050063)
64
divyadesai81bb7ba2020-03-11 11:45:23 +000065type LogLevel int8
66
Don Newton7577f072020-01-06 12:41:11 -050067const (
68 // DebugLevel logs a message at debug level
divyadesai81bb7ba2020-03-11 11:45:23 +000069 DebugLevel = LogLevel(iota)
Don Newton7577f072020-01-06 12:41:11 -050070 // 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
Don Newton7577f072020-01-06 12:41:11 -050076 // 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
Rohan Agrawalc32d9932020-06-15 11:01:47 +000086// Context Aware Logger represents an abstract logging interface. Any logging implementation used
Don Newton7577f072020-01-06 12:41:11 -050087// will need to abide by this interface
Rohan Agrawalc32d9932020-06-15 11:01:47 +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)
Don Newton7577f072020-01-06 12:41:11 -050093
Rohan Agrawalc32d9932020-06-15 11:01:47 +000094 Info(context.Context, ...interface{})
95 Infoln(context.Context, ...interface{})
96 Infof(context.Context, string, ...interface{})
97 Infow(context.Context, string, Fields)
Don Newton7577f072020-01-06 12:41:11 -050098
Rohan Agrawalc32d9932020-06-15 11:01:47 +000099 Warn(context.Context, ...interface{})
100 Warnln(context.Context, ...interface{})
101 Warnf(context.Context, string, ...interface{})
102 Warnw(context.Context, string, Fields)
Don Newton7577f072020-01-06 12:41:11 -0500103
Rohan Agrawalc32d9932020-06-15 11:01:47 +0000104 Error(context.Context, ...interface{})
105 Errorln(context.Context, ...interface{})
106 Errorf(context.Context, string, ...interface{})
107 Errorw(context.Context, string, Fields)
Don Newton7577f072020-01-06 12:41:11 -0500108
Rohan Agrawalc32d9932020-06-15 11:01:47 +0000109 Fatal(context.Context, ...interface{})
110 Fatalln(context.Context, ...interface{})
111 Fatalf(context.Context, string, ...interface{})
112 Fatalw(context.Context, string, Fields)
Don Newton7577f072020-01-06 12:41:11 -0500113
Rohan Agrawalc32d9932020-06-15 11:01:47 +0000114 With(Fields) CLogger
Don Newton7577f072020-01-06 12:41:11 -0500115
116 // The following are added to be able to use this logger as a gRPC LoggerV2 if needed
117 //
Rohan Agrawalc32d9932020-06-15 11:01:47 +0000118 Warning(context.Context, ...interface{})
119 Warningln(context.Context, ...interface{})
120 Warningf(context.Context, string, ...interface{})
Don Newton7577f072020-01-06 12:41:11 -0500121
122 // V reports whether verbosity level l is at least the requested verbose level.
divyadesai81bb7ba2020-03-11 11:45:23 +0000123 V(l LogLevel) bool
David K. Bainbridgeaea73cd2020-01-27 10:44:50 -0800124
125 //Returns the log level of this specific logger
divyadesai81bb7ba2020-03-11 11:45:23 +0000126 GetLogLevel() LogLevel
Don Newton7577f072020-01-06 12:41:11 -0500127}
128
129// Fields is used as key-value pairs for structured logging
130type Fields map[string]interface{}
131
Rohan Agrawalc32d9932020-06-15 11:01:47 +0000132var defaultLogger *clogger
Don Newton7577f072020-01-06 12:41:11 -0500133var cfg zp.Config
134
Rohan Agrawalc32d9932020-06-15 11:01:47 +0000135var loggers map[string]*clogger
Don Newton7577f072020-01-06 12:41:11 -0500136var cfgs map[string]zp.Config
137
Rohan Agrawalc32d9932020-06-15 11:01:47 +0000138type clogger struct {
David K. Bainbridgeaea73cd2020-01-27 10:44:50 -0800139 log *zp.SugaredLogger
140 parent *zp.Logger
141 packageName string
Don Newton7577f072020-01-06 12:41:11 -0500142}
143
divyadesai81bb7ba2020-03-11 11:45:23 +0000144func logLevelToAtomicLevel(l LogLevel) zp.AtomicLevel {
Don Newton7577f072020-01-06 12:41:11 -0500145 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)
Don Newton7577f072020-01-06 12:41:11 -0500154 case FatalLevel:
155 return zp.NewAtomicLevelAt(zc.FatalLevel)
156 }
157 return zp.NewAtomicLevelAt(zc.ErrorLevel)
158}
159
divyadesai81bb7ba2020-03-11 11:45:23 +0000160func logLevelToLevel(l LogLevel) zc.Level {
Don Newton7577f072020-01-06 12:41:11 -0500161 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
Don Newton7577f072020-01-06 12:41:11 -0500170 case FatalLevel:
171 return zc.FatalLevel
172 }
173 return zc.ErrorLevel
174}
175
divyadesai81bb7ba2020-03-11 11:45:23 +0000176func levelToLogLevel(l zc.Level) LogLevel {
Don Newton7577f072020-01-06 12:41:11 -0500177 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
David K. Bainbridgeaea73cd2020-01-27 10:44:50 -0800186 case zc.FatalLevel:
187 return FatalLevel
188 }
189 return ErrorLevel
190}
191
divyadesai81bb7ba2020-03-11 11:45:23 +0000192func StringToLogLevel(l string) (LogLevel, error) {
193 switch strings.ToUpper(l) {
David K. Bainbridgeaea73cd2020-01-27 10:44:50 -0800194 case "DEBUG":
divyadesai81bb7ba2020-03-11 11:45:23 +0000195 return DebugLevel, nil
David K. Bainbridgeaea73cd2020-01-27 10:44:50 -0800196 case "INFO":
divyadesai81bb7ba2020-03-11 11:45:23 +0000197 return InfoLevel, nil
David K. Bainbridgeaea73cd2020-01-27 10:44:50 -0800198 case "WARN":
divyadesai81bb7ba2020-03-11 11:45:23 +0000199 return WarnLevel, nil
David K. Bainbridgeaea73cd2020-01-27 10:44:50 -0800200 case "ERROR":
divyadesai81bb7ba2020-03-11 11:45:23 +0000201 return ErrorLevel, nil
David K. Bainbridgeaea73cd2020-01-27 10:44:50 -0800202 case "FATAL":
divyadesai81bb7ba2020-03-11 11:45:23 +0000203 return FatalLevel, nil
Don Newton7577f072020-01-06 12:41:11 -0500204 }
divyadesai81bb7ba2020-03-11 11:45:23 +0000205 return 0, errors.New("Given LogLevel is invalid : " + l)
Don Newton7577f072020-01-06 12:41:11 -0500206}
207
divyadesai81bb7ba2020-03-11 11:45:23 +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. Bainbridge595b6702021-04-09 16:10:58 +0000221 return "", fmt.Errorf("Given LogLevel is invalid %d", l)
divyadesai81bb7ba2020-03-11 11:45:23 +0000222}
223
224func getDefaultConfig(outputType string, level LogLevel, defaultFields Fields) zp.Config {
Don Newton7577f072020-01-06 12:41:11 -0500225 return zp.Config{
divyadesai81bb7ba2020-03-11 11:45:23 +0000226 Level: logLevelToAtomicLevel(level),
Don Newton7577f072020-01-06 12:41:11 -0500227 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",
divyadesai81bb7ba2020-03-11 11:45:23 +0000236 CallerKey: "caller",
Don Newton7577f072020-01-06 12:41:11 -0500237 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 Agrawal00d3a412020-04-22 10:51:39 +0000247func ConstructZapConfig(outputType string, level LogLevel, fields Fields) zp.Config {
248 return getDefaultConfig(outputType, level, fields)
249}
250
Don Newton7577f072020-01-06 12:41:11 -0500251// SetLogger needs to be invoked before the logger API can be invoked. This function
252// initialize the default logger (zap's sugaredlogger)
Rohan Agrawalc32d9932020-06-15 11:01:47 +0000253func SetDefaultLogger(outputType string, level LogLevel, defaultFields Fields) (CLogger, error) {
Don Newton7577f072020-01-06 12:41:11 -0500254 // Build a custom config using zap
255 cfg = getDefaultConfig(outputType, level, defaultFields)
256
divyadesai81bb7ba2020-03-11 11:45:23 +0000257 l, err := cfg.Build(zp.AddCallerSkip(1))
Don Newton7577f072020-01-06 12:41:11 -0500258 if err != nil {
259 return nil, err
260 }
261
Rohan Agrawalc32d9932020-06-15 11:01:47 +0000262 defaultLogger = &clogger{
Don Newton7577f072020-01-06 12:41:11 -0500263 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.
Rohan Agrawalc32d9932020-06-15 11:01:47 +0000279func RegisterPackage(outputType string, level LogLevel, defaultFields Fields, pkgNames ...string) (CLogger, error) {
Don Newton7577f072020-01-06 12:41:11 -0500280 if cfgs == nil {
281 cfgs = make(map[string]zp.Config)
282 }
283 if loggers == nil {
Rohan Agrawalc32d9932020-06-15 11:01:47 +0000284 loggers = make(map[string]*clogger)
Don Newton7577f072020-01-06 12:41:11 -0500285 }
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
divyadesai81bb7ba2020-03-11 11:45:23 +0000302 l, err := cfgs[pkgName].Build(zp.AddCallerSkip(1))
Don Newton7577f072020-01-06 12:41:11 -0500303 if err != nil {
304 return nil, err
305 }
306
Rohan Agrawalc32d9932020-06-15 11:01:47 +0000307 loggers[pkgName] = &clogger{
David K. Bainbridgeaea73cd2020-01-27 10:44:50 -0800308 log: l.Sugar(),
309 parent: l,
310 packageName: pkgName,
Don Newton7577f072020-01-06 12:41:11 -0500311 }
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 }
divyadesai81bb7ba2020-03-11 11:45:23 +0000324 l, err := cfg.Build(zp.AddCallerSkip(1))
Don Newton7577f072020-01-06 12:41:11 -0500325 if err != nil {
326 return err
327 }
328
divyadesai81bb7ba2020-03-11 11:45:23 +0000329 // Update the existing zap logger instance
330 loggers[pkgName].log = l.Sugar()
331 loggers[pkgName].parent = l
Don Newton7577f072020-01-06 12:41:11 -0500332 }
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
divyadesai81bb7ba2020-03-11 11:45:23 +0000347// UpdateLogger updates the logger associated with a caller's package with supplied defaultFields
348func UpdateLogger(defaultFields Fields) error {
Don Newton7577f072020-01-06 12:41:11 -0500349 pkgName, _, _, _ := getCallerInfo()
350 if _, exist := loggers[pkgName]; !exist {
divyadesai81bb7ba2020-03-11 11:45:23 +0000351 return fmt.Errorf("package-%s-not-registered", pkgName)
Don Newton7577f072020-01-06 12:41:11 -0500352 }
353
354 // Build a new logger
355 if _, exist := cfgs[pkgName]; !exist {
divyadesai81bb7ba2020-03-11 11:45:23 +0000356 return fmt.Errorf("config-%s-not-registered", pkgName)
Don Newton7577f072020-01-06 12:41:11 -0500357 }
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 }
divyadesai81bb7ba2020-03-11 11:45:23 +0000366 l, err := cfg.Build(zp.AddCallerSkip(1))
Don Newton7577f072020-01-06 12:41:11 -0500367 if err != nil {
divyadesai81bb7ba2020-03-11 11:45:23 +0000368 return err
Don Newton7577f072020-01-06 12:41:11 -0500369 }
370
divyadesai81bb7ba2020-03-11 11:45:23 +0000371 // Update the existing zap logger instance
372 loggers[pkgName].log = l.Sugar()
373 loggers[pkgName].parent = l
374
375 return nil
Don Newton7577f072020-01-06 12:41:11 -0500376}
377
divyadesai81bb7ba2020-03-11 11:45:23 +0000378func setLevel(cfg zp.Config, level LogLevel) {
Don Newton7577f072020-01-06 12:41:11 -0500379 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)
Don Newton7577f072020-01-06 12:41:11 -0500388 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
divyadesai81bb7ba2020-03-11 11:45:23 +0000397func SetPackageLogLevel(packageName string, level LogLevel) {
Don Newton7577f072020-01-06 12:41:11 -0500398 // 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
divyadesai81bb7ba2020-03-11 11:45:23 +0000405func SetAllLogLevel(level LogLevel) {
Don Newton7577f072020-01-06 12:41:11 -0500406 // 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.
divyadesai81bb7ba2020-03-11 11:45:23 +0000413func GetPackageLogLevel(packageName ...string) (LogLevel, error) {
Don Newton7577f072020-01-06 12:41:11 -0500414 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 {
divyadesai81bb7ba2020-03-11 11:45:23 +0000421 return levelToLogLevel(cfg.Level.Level()), nil
Don Newton7577f072020-01-06 12:41:11 -0500422 }
divyadesai81bb7ba2020-03-11 11:45:23 +0000423 return 0, fmt.Errorf("unknown-package-%s", name)
Don Newton7577f072020-01-06 12:41:11 -0500424}
425
426//GetDefaultLogLevel gets the log level used for packages that don't have specific loggers
divyadesai81bb7ba2020-03-11 11:45:23 +0000427func GetDefaultLogLevel() LogLevel {
428 return levelToLogLevel(cfg.Level.Level())
Don Newton7577f072020-01-06 12:41:11 -0500429}
430
431//SetLogLevel sets the log level for the logger corresponding to the caller's package
divyadesai81bb7ba2020-03-11 11:45:23 +0000432func SetLogLevel(level LogLevel) error {
Don Newton7577f072020-01-06 12:41:11 -0500433 pkgName, _, _, _ := getCallerInfo()
434 if _, exist := cfgs[pkgName]; !exist {
divyadesai81bb7ba2020-03-11 11:45:23 +0000435 return fmt.Errorf("unregistered-package-%s", pkgName)
Don Newton7577f072020-01-06 12:41:11 -0500436 }
437 cfg := cfgs[pkgName]
438 setLevel(cfg, level)
439 return nil
440}
441
442//SetDefaultLogLevel sets the log level used for packages that don't have specific loggers
divyadesai81bb7ba2020-03-11 11:45:23 +0000443func SetDefaultLogLevel(level LogLevel) {
Don Newton7577f072020-01-06 12:41:11 -0500444 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
Don Newton7577f072020-01-06 12:41:11 -0500517// With returns a logger initialized with the key-value pairs
Rohan Agrawalc32d9932020-06-15 11:01:47 +0000518func (l clogger) With(keysAndValues Fields) CLogger {
519 return clogger{log: l.log.With(serializeMap(keysAndValues)...), parent: l.parent}
Don Newton7577f072020-01-06 12:41:11 -0500520}
521
522// Debug logs a message at level Debug on the standard logger.
Rohan Agrawalc32d9932020-06-15 11:01:47 +0000523func (l clogger) Debug(ctx context.Context, args ...interface{}) {
Girish Kumarcd402012020-08-18 12:17:38 +0000524 l.log.With(GetGlobalLFM().ExtractContextAttributes(ctx)...).Debug(args...)
Don Newton7577f072020-01-06 12:41:11 -0500525}
526
527// Debugln logs a message at level Debug on the standard logger with a line feed. Default in any case.
Rohan Agrawalc32d9932020-06-15 11:01:47 +0000528func (l clogger) Debugln(ctx context.Context, args ...interface{}) {
Girish Kumarcd402012020-08-18 12:17:38 +0000529 l.log.With(GetGlobalLFM().ExtractContextAttributes(ctx)...).Debug(args...)
Don Newton7577f072020-01-06 12:41:11 -0500530}
531
532// Debugw logs a message at level Debug on the standard logger.
Rohan Agrawalc32d9932020-06-15 11:01:47 +0000533func (l clogger) Debugf(ctx context.Context, format string, args ...interface{}) {
Girish Kumarcd402012020-08-18 12:17:38 +0000534 l.log.With(GetGlobalLFM().ExtractContextAttributes(ctx)...).Debugf(format, args...)
Don Newton7577f072020-01-06 12:41:11 -0500535}
536
537// Debugw logs a message with some additional context. The variadic key-value
538// pairs are treated as they are in With.
Rohan Agrawalc32d9932020-06-15 11:01:47 +0000539func (l clogger) Debugw(ctx context.Context, msg string, keysAndValues Fields) {
Neha Sharma87d43d72020-04-08 14:10:40 +0000540 if l.V(DebugLevel) {
Girish Kumarcd402012020-08-18 12:17:38 +0000541 l.log.With(GetGlobalLFM().ExtractContextAttributes(ctx)...).Debugw(msg, serializeMap(keysAndValues)...)
Neha Sharma87d43d72020-04-08 14:10:40 +0000542 }
Don Newton7577f072020-01-06 12:41:11 -0500543}
544
545// Info logs a message at level Info on the standard logger.
Rohan Agrawalc32d9932020-06-15 11:01:47 +0000546func (l clogger) Info(ctx context.Context, args ...interface{}) {
Girish Kumarcd402012020-08-18 12:17:38 +0000547 l.log.With(GetGlobalLFM().ExtractContextAttributes(ctx)...).Info(args...)
Don Newton7577f072020-01-06 12:41:11 -0500548}
549
550// Infoln logs a message at level Info on the standard logger with a line feed. Default in any case.
Rohan Agrawalc32d9932020-06-15 11:01:47 +0000551func (l clogger) Infoln(ctx context.Context, args ...interface{}) {
Girish Kumarcd402012020-08-18 12:17:38 +0000552 l.log.With(GetGlobalLFM().ExtractContextAttributes(ctx)...).Info(args...)
Don Newton7577f072020-01-06 12:41:11 -0500553 //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.
Rohan Agrawalc32d9932020-06-15 11:01:47 +0000558func (l clogger) Infof(ctx context.Context, format string, args ...interface{}) {
Girish Kumarcd402012020-08-18 12:17:38 +0000559 l.log.With(GetGlobalLFM().ExtractContextAttributes(ctx)...).Infof(format, args...)
Don Newton7577f072020-01-06 12:41:11 -0500560}
561
562// Infow logs a message with some additional context. The variadic key-value
563// pairs are treated as they are in With.
Rohan Agrawalc32d9932020-06-15 11:01:47 +0000564func (l clogger) Infow(ctx context.Context, msg string, keysAndValues Fields) {
Neha Sharma87d43d72020-04-08 14:10:40 +0000565 if l.V(InfoLevel) {
Girish Kumarcd402012020-08-18 12:17:38 +0000566 l.log.With(GetGlobalLFM().ExtractContextAttributes(ctx)...).Infow(msg, serializeMap(keysAndValues)...)
Neha Sharma87d43d72020-04-08 14:10:40 +0000567 }
Don Newton7577f072020-01-06 12:41:11 -0500568}
569
570// Warn logs a message at level Warn on the standard logger.
Rohan Agrawalc32d9932020-06-15 11:01:47 +0000571func (l clogger) Warn(ctx context.Context, args ...interface{}) {
Girish Kumarcd402012020-08-18 12:17:38 +0000572 l.log.With(GetGlobalLFM().ExtractContextAttributes(ctx)...).Warn(args...)
Don Newton7577f072020-01-06 12:41:11 -0500573}
574
575// Warnln logs a message at level Warn on the standard logger with a line feed. Default in any case.
Rohan Agrawalc32d9932020-06-15 11:01:47 +0000576func (l clogger) Warnln(ctx context.Context, args ...interface{}) {
Girish Kumarcd402012020-08-18 12:17:38 +0000577 l.log.With(GetGlobalLFM().ExtractContextAttributes(ctx)...).Warn(args...)
Don Newton7577f072020-01-06 12:41:11 -0500578}
579
580// Warnf logs a message at level Warn on the standard logger.
Rohan Agrawalc32d9932020-06-15 11:01:47 +0000581func (l clogger) Warnf(ctx context.Context, format string, args ...interface{}) {
Girish Kumarcd402012020-08-18 12:17:38 +0000582 l.log.With(GetGlobalLFM().ExtractContextAttributes(ctx)...).Warnf(format, args...)
Don Newton7577f072020-01-06 12:41:11 -0500583}
584
585// Warnw logs a message with some additional context. The variadic key-value
586// pairs are treated as they are in With.
Rohan Agrawalc32d9932020-06-15 11:01:47 +0000587func (l clogger) Warnw(ctx context.Context, msg string, keysAndValues Fields) {
Neha Sharma87d43d72020-04-08 14:10:40 +0000588 if l.V(WarnLevel) {
Girish Kumarcd402012020-08-18 12:17:38 +0000589 l.log.With(GetGlobalLFM().ExtractContextAttributes(ctx)...).Warnw(msg, serializeMap(keysAndValues)...)
Neha Sharma87d43d72020-04-08 14:10:40 +0000590 }
Don Newton7577f072020-01-06 12:41:11 -0500591}
592
593// Error logs a message at level Error on the standard logger.
Rohan Agrawalc32d9932020-06-15 11:01:47 +0000594func (l clogger) Error(ctx context.Context, args ...interface{}) {
Girish Kumarcd402012020-08-18 12:17:38 +0000595 l.log.With(GetGlobalLFM().ExtractContextAttributes(ctx)...).Error(args...)
Don Newton7577f072020-01-06 12:41:11 -0500596}
597
598// Errorln logs a message at level Error on the standard logger with a line feed. Default in any case.
Rohan Agrawalc32d9932020-06-15 11:01:47 +0000599func (l clogger) Errorln(ctx context.Context, args ...interface{}) {
Girish Kumarcd402012020-08-18 12:17:38 +0000600 l.log.With(GetGlobalLFM().ExtractContextAttributes(ctx)...).Error(args...)
Don Newton7577f072020-01-06 12:41:11 -0500601}
602
603// Errorf logs a message at level Error on the standard logger.
Rohan Agrawalc32d9932020-06-15 11:01:47 +0000604func (l clogger) Errorf(ctx context.Context, format string, args ...interface{}) {
Girish Kumarcd402012020-08-18 12:17:38 +0000605 l.log.With(GetGlobalLFM().ExtractContextAttributes(ctx)...).Errorf(format, args...)
Don Newton7577f072020-01-06 12:41:11 -0500606}
607
608// Errorw logs a message with some additional context. The variadic key-value
609// pairs are treated as they are in With.
Rohan Agrawalc32d9932020-06-15 11:01:47 +0000610func (l clogger) Errorw(ctx context.Context, msg string, keysAndValues Fields) {
Neha Sharma87d43d72020-04-08 14:10:40 +0000611 if l.V(ErrorLevel) {
Girish Kumarcd402012020-08-18 12:17:38 +0000612 l.log.With(GetGlobalLFM().ExtractContextAttributes(ctx)...).Errorw(msg, serializeMap(keysAndValues)...)
Neha Sharma87d43d72020-04-08 14:10:40 +0000613 }
Don Newton7577f072020-01-06 12:41:11 -0500614}
615
616// Fatal logs a message at level Fatal on the standard logger.
Rohan Agrawalc32d9932020-06-15 11:01:47 +0000617func (l clogger) Fatal(ctx context.Context, args ...interface{}) {
Girish Kumarcd402012020-08-18 12:17:38 +0000618 l.log.With(GetGlobalLFM().ExtractContextAttributes(ctx)...).Fatal(args...)
Don Newton7577f072020-01-06 12:41:11 -0500619}
620
621// Fatalln logs a message at level Fatal on the standard logger with a line feed. Default in any case.
Rohan Agrawalc32d9932020-06-15 11:01:47 +0000622func (l clogger) Fatalln(ctx context.Context, args ...interface{}) {
Girish Kumarcd402012020-08-18 12:17:38 +0000623 l.log.With(GetGlobalLFM().ExtractContextAttributes(ctx)...).Fatal(args...)
Don Newton7577f072020-01-06 12:41:11 -0500624}
625
626// Fatalf logs a message at level Fatal on the standard logger.
Rohan Agrawalc32d9932020-06-15 11:01:47 +0000627func (l clogger) Fatalf(ctx context.Context, format string, args ...interface{}) {
Girish Kumarcd402012020-08-18 12:17:38 +0000628 l.log.With(GetGlobalLFM().ExtractContextAttributes(ctx)...).Fatalf(format, args...)
Don Newton7577f072020-01-06 12:41:11 -0500629}
630
631// Fatalw logs a message with some additional context. The variadic key-value
632// pairs are treated as they are in With.
Rohan Agrawalc32d9932020-06-15 11:01:47 +0000633func (l clogger) Fatalw(ctx context.Context, msg string, keysAndValues Fields) {
Neha Sharma87d43d72020-04-08 14:10:40 +0000634 if l.V(FatalLevel) {
Girish Kumarcd402012020-08-18 12:17:38 +0000635 l.log.With(GetGlobalLFM().ExtractContextAttributes(ctx)...).Fatalw(msg, serializeMap(keysAndValues)...)
Neha Sharma87d43d72020-04-08 14:10:40 +0000636 }
Don Newton7577f072020-01-06 12:41:11 -0500637}
638
639// Warning logs a message at level Warn on the standard logger.
Rohan Agrawalc32d9932020-06-15 11:01:47 +0000640func (l clogger) Warning(ctx context.Context, args ...interface{}) {
Girish Kumarcd402012020-08-18 12:17:38 +0000641 l.log.With(GetGlobalLFM().ExtractContextAttributes(ctx)...).Warn(args...)
Don Newton7577f072020-01-06 12:41:11 -0500642}
643
644// Warningln logs a message at level Warn on the standard logger with a line feed. Default in any case.
Rohan Agrawalc32d9932020-06-15 11:01:47 +0000645func (l clogger) Warningln(ctx context.Context, args ...interface{}) {
Girish Kumarcd402012020-08-18 12:17:38 +0000646 l.log.With(GetGlobalLFM().ExtractContextAttributes(ctx)...).Warn(args...)
Don Newton7577f072020-01-06 12:41:11 -0500647}
648
649// Warningf logs a message at level Warn on the standard logger.
Rohan Agrawalc32d9932020-06-15 11:01:47 +0000650func (l clogger) Warningf(ctx context.Context, format string, args ...interface{}) {
Girish Kumarcd402012020-08-18 12:17:38 +0000651 l.log.With(GetGlobalLFM().ExtractContextAttributes(ctx)...).Warnf(format, args...)
Don Newton7577f072020-01-06 12:41:11 -0500652}
653
654// V reports whether verbosity level l is at least the requested verbose level.
Rohan Agrawalc32d9932020-06-15 11:01:47 +0000655func (l clogger) V(level LogLevel) bool {
divyadesai81bb7ba2020-03-11 11:45:23 +0000656 return l.parent.Core().Enabled(logLevelToLevel(level))
Don Newton7577f072020-01-06 12:41:11 -0500657}
658
David K. Bainbridgeaea73cd2020-01-27 10:44:50 -0800659// GetLogLevel returns the current level of the logger
Rohan Agrawalc32d9932020-06-15 11:01:47 +0000660func (l clogger) GetLogLevel() LogLevel {
divyadesai81bb7ba2020-03-11 11:45:23 +0000661 return levelToLogLevel(cfgs[l.packageName].Level.Level())
David K. Bainbridgeaea73cd2020-01-27 10:44:50 -0800662}