4daef3a1ad09c797db25b7910562f7a5f3c640eb
[icn/sdwan.git] /
1 // SPDX-License-Identifier: Apache-2.0
2 // Copyright (c) 2020 Intel Corporation
3
4 package logutils
5
6 import (
7         "fmt"
8         "path"
9         "runtime"
10         "strings"
11
12         "gitlab.com/project-emco/core/emco-base/src/orchestrator/pkg/infra/config"
13         log "github.com/sirupsen/logrus"
14 )
15
16 //Fields is type that will be used by the calling function
17 type Fields map[string]interface{}
18
19 func init() {
20         // Log as JSON instead of the default ASCII formatter.
21         log.SetFormatter(&log.JSONFormatter{TimestampFormat: "2006-01-02T15:04:05.999999999Z07:00"})
22         if strings.EqualFold(config.GetConfiguration().LogLevel, "warn") {
23                 log.SetLevel(log.WarnLevel)
24
25         }
26         if strings.EqualFold(config.GetConfiguration().LogLevel, "info") {
27                 log.SetLevel(log.InfoLevel)
28         }
29 }
30
31 // Error uses the fields provided and logs
32 func Error(msg string, fields Fields) {
33         if pc, file, line, ok := runtime.Caller(1); ok {
34                 if fields != nil {
35                         fields["SOURCE"] = fmt.Sprintf("file[%s:%d] func[%s]", path.Base(file), line, path.Base(runtime.FuncForPC(pc).Name()))
36                 }
37                 log.WithFields(log.Fields(fields)).Error(msg)
38         } else {
39                 log.WithFields(log.Fields(fields)).Error(msg)
40         }
41 }
42
43 // Warn uses the fields provided and logs
44 func Warn(msg string, fields Fields) {
45         if pc, file, line, ok := runtime.Caller(1); ok {
46                 if fields != nil {
47                         fields["SOURCE"] = fmt.Sprintf("file[%s:%d] func[%s]", path.Base(file), line, path.Base(runtime.FuncForPC(pc).Name()))
48                 }
49                 log.WithFields(log.Fields(fields)).Warn(msg)
50         } else {
51                 log.WithFields(log.Fields(fields)).Warn(msg)
52         }
53 }
54
55 // Info uses the fields provided and logs
56 func Info(msg string, fields Fields) {
57         if pc, file, line, ok := runtime.Caller(1); ok {
58                 if fields != nil {
59                         fields["SOURCE"] = fmt.Sprintf("file[%s:%d] func[%s]", path.Base(file), line, path.Base(runtime.FuncForPC(pc).Name()))
60                 }
61                 log.WithFields(log.Fields(fields)).Info(msg)
62         } else {
63                 log.WithFields(log.Fields(fields)).Info(msg)
64         }
65 }
66
67 // SetLoglevel .. Set Log level
68 func SetLoglevel(level log.Level) {
69         log.SetLevel(level)
70 }