Skip to content

Commit

Permalink
Replace logrus with zap logger (#224)
Browse files Browse the repository at this point in the history
Signed-off-by: Arrobo, Gabriel <[email protected]>
  • Loading branch information
gab-arrobo authored Oct 2, 2024
1 parent a71d6ae commit a52245f
Show file tree
Hide file tree
Showing 11 changed files with 129 additions and 162 deletions.
2 changes: 1 addition & 1 deletion VERSION
Original file line number Diff line number Diff line change
@@ -1 +1 @@
1.4.4-dev
1.5.0
5 changes: 3 additions & 2 deletions backend/factory/factory.go
Original file line number Diff line number Diff line change
Expand Up @@ -15,6 +15,7 @@ import (
"fmt"
"os"

"github.com/omec-project/webconsole/backend/logger"
"gopkg.in/yaml.v2"
)

Expand Down Expand Up @@ -46,11 +47,11 @@ func InitConfigFactory(f string) error {
// we dont want Mode5G coming from the helm chart, since
// there is chance of misconfiguration
if os.Getenv("CONFIGPOD_DEPLOYMENT") == "4G" {
fmt.Println("ConfigPod running in 4G deployment")
logger.ConfigLog.Infoln("configPod running in 4G deployment")
WebUIConfig.Configuration.Mode5G = false
} else {
// default mode
fmt.Println("ConfigPod running in 5G deployment")
logger.ConfigLog.Infoln("configPod running in 5G deployment")
WebUIConfig.Configuration.Mode5G = true
}
}
Expand Down
91 changes: 46 additions & 45 deletions backend/logger/logger.go
Original file line number Diff line number Diff line change
Expand Up @@ -7,64 +7,65 @@
package logger

import (
"os"
"time"

formatter "github.com/antonfisher/nested-logrus-formatter"
logger_util "github.com/omec-project/util/logger"
"github.com/omec-project/util/logger_conf"
"github.com/sirupsen/logrus"
"go.uber.org/zap"
"go.uber.org/zap/zapcore"
)

var (
log *logrus.Logger
AppLog *logrus.Entry
InitLog *logrus.Entry
WebUILog *logrus.Entry
ContextLog *logrus.Entry
GinLog *logrus.Entry
GrpcLog *logrus.Entry
ConfigLog *logrus.Entry
DbLog *logrus.Entry
log *zap.Logger
AppLog *zap.SugaredLogger
InitLog *zap.SugaredLogger
WebUILog *zap.SugaredLogger
ContextLog *zap.SugaredLogger
GinLog *zap.SugaredLogger
GrpcLog *zap.SugaredLogger
ConfigLog *zap.SugaredLogger
DbLog *zap.SugaredLogger
atomicLevel zap.AtomicLevel
)

func init() {
log = logrus.New()
log.SetReportCaller(false)

log.Formatter = &formatter.Formatter{
TimestampFormat: time.RFC3339,
TrimMessages: true,
NoFieldsSpace: true,
HideKeys: true,
FieldsOrder: []string{"component", "category"},
atomicLevel = zap.NewAtomicLevelAt(zap.InfoLevel)
config := zap.Config{
Level: atomicLevel,
Development: false,
Encoding: "console",
EncoderConfig: zap.NewProductionEncoderConfig(),
OutputPaths: []string{"stdout"},
ErrorOutputPaths: []string{"stderr"},
}

free5gcLogHook, err := logger_util.NewFileHook(logger_conf.Free5gcLogFile, os.O_CREATE|os.O_APPEND|os.O_RDWR, 0o666)
if err == nil {
log.Hooks.Add(free5gcLogHook)
}
config.EncoderConfig.TimeKey = "timestamp"
config.EncoderConfig.EncodeTime = zapcore.ISO8601TimeEncoder
config.EncoderConfig.LevelKey = "level"
config.EncoderConfig.EncodeLevel = zapcore.CapitalLevelEncoder
config.EncoderConfig.CallerKey = "caller"
config.EncoderConfig.EncodeCaller = zapcore.ShortCallerEncoder
config.EncoderConfig.MessageKey = "message"
config.EncoderConfig.StacktraceKey = ""

selfLogHook, err := logger_util.NewFileHook(
logger_conf.Free5gcLogDir+"webconsole.log", os.O_CREATE|os.O_APPEND|os.O_RDWR, 0o666)
if err == nil {
log.Hooks.Add(selfLogHook)
var err error
log, err = config.Build()
if err != nil {
panic(err)
}

AppLog = log.WithFields(logrus.Fields{"component": "WebUI", "category": "App"})
InitLog = log.WithFields(logrus.Fields{"component": "WebUI", "category": "Init"})
WebUILog = log.WithFields(logrus.Fields{"component": "WebUI", "category": "WebUI"})
ContextLog = log.WithFields(logrus.Fields{"component": "WebUI", "category": "Context"})
GinLog = log.WithFields(logrus.Fields{"component": "WebUI", "category": "GIN"})
GrpcLog = log.WithFields(logrus.Fields{"component": "WebUI", "category": "GRPC"})
ConfigLog = log.WithFields(logrus.Fields{"component": "WebUI", "category": "CONFIG"})
DbLog = log.WithFields(logrus.Fields{"component": "WebUI", "category": "DB"})
AppLog = log.Sugar().With("component", "WebUI", "category", "App")
InitLog = log.Sugar().With("component", "WebUI", "category", "Init")
WebUILog = log.Sugar().With("component", "WebUI", "category", "WebUI")
ContextLog = log.Sugar().With("component", "WebUI", "category", "Context")
GinLog = log.Sugar().With("component", "WebUI", "category", "GIN")
GrpcLog = log.Sugar().With("component", "WebUI", "category", "GRPC")
ConfigLog = log.Sugar().With("component", "WebUI", "category", "CONFIG")
DbLog = log.Sugar().With("component", "WebUI", "category", "DB")
}

func SetLogLevel(level logrus.Level) {
log.SetLevel(level)
func GetLogger() *zap.Logger {
return log
}

func SetReportCaller(set bool) {
log.SetReportCaller(set)
// SetLogLevel: set the log level (panic|fatal|error|warn|info|debug)
func SetLogLevel(level zapcore.Level) {
InitLog.Infoln("set log level:", level)
atomicLevel.SetLevel(level)
}
67 changes: 23 additions & 44 deletions backend/webui_service/webui_init.go
Original file line number Diff line number Diff line change
Expand Up @@ -19,9 +19,8 @@ import (

"github.com/gin-contrib/cors"
"github.com/omec-project/util/http2_util"
loggerUtil "github.com/omec-project/util/logger"
utilLogger "github.com/omec-project/util/logger"
"github.com/omec-project/util/path_util"
pathUtilLogger "github.com/omec-project/util/path_util/logger"
"github.com/omec-project/webconsole/backend/factory"
"github.com/omec-project/webconsole/backend/logger"
"github.com/omec-project/webconsole/backend/metrics"
Expand All @@ -30,8 +29,9 @@ import (
"github.com/omec-project/webconsole/configmodels"
"github.com/omec-project/webconsole/dbadapter"
gServ "github.com/omec-project/webconsole/proto/server"
"github.com/sirupsen/logrus"
"github.com/urfave/cli"
"go.uber.org/zap"
"go.uber.org/zap/zapcore"
)

type WEBUI struct{}
Expand All @@ -56,7 +56,7 @@ var webuiCLi = []cli.Flag{
},
}

var initLog *logrus.Entry
var initLog *zap.SugaredLogger

func init() {
initLog = logger.InitLog
Expand Down Expand Up @@ -93,51 +93,33 @@ func (webui *WEBUI) setLogLevel() {

if factory.WebUIConfig.Logger.WEBUI != nil {
if factory.WebUIConfig.Logger.WEBUI.DebugLevel != "" {
if level, err := logrus.ParseLevel(factory.WebUIConfig.Logger.WEBUI.DebugLevel); err != nil {
if level, err := zapcore.ParseLevel(factory.WebUIConfig.Logger.WEBUI.DebugLevel); err != nil {
initLog.Warnf("WebUI Log level [%s] is invalid, set to [info] level",
factory.WebUIConfig.Logger.WEBUI.DebugLevel)
logger.SetLogLevel(logrus.InfoLevel)
logger.SetLogLevel(zap.InfoLevel)
} else {
initLog.Infof("WebUI Log level is set to [%s] level", level)
logger.SetLogLevel(level)
}
} else {
initLog.Warnln("WebUI Log level not set. Default set to [info] level")
logger.SetLogLevel(logrus.InfoLevel)
logger.SetLogLevel(zap.InfoLevel)
}
logger.SetReportCaller(factory.WebUIConfig.Logger.WEBUI.ReportCaller)
}

if factory.WebUIConfig.Logger.PathUtil != nil {
if factory.WebUIConfig.Logger.PathUtil.DebugLevel != "" {
if level, err := logrus.ParseLevel(factory.WebUIConfig.Logger.PathUtil.DebugLevel); err != nil {
pathUtilLogger.PathLog.Warnf("PathUtil Log level [%s] is invalid, set to [info] level",
factory.WebUIConfig.Logger.PathUtil.DebugLevel)
pathUtilLogger.SetLogLevel(logrus.InfoLevel)
} else {
pathUtilLogger.SetLogLevel(level)
}
} else {
pathUtilLogger.PathLog.Warnln("PathUtil Log level not set. Default set to [info] level")
pathUtilLogger.SetLogLevel(logrus.InfoLevel)
}
pathUtilLogger.SetReportCaller(factory.WebUIConfig.Logger.PathUtil.ReportCaller)
}

if factory.WebUIConfig.Logger.MongoDBLibrary != nil {
if factory.WebUIConfig.Logger.MongoDBLibrary.DebugLevel != "" {
if level, err := logrus.ParseLevel(factory.WebUIConfig.Logger.MongoDBLibrary.DebugLevel); err != nil {
loggerUtil.AppLog.Warnf("MongoDBLibrary Log level [%s] is invalid, set to [info] level",
if level, err := zapcore.ParseLevel(factory.WebUIConfig.Logger.MongoDBLibrary.DebugLevel); err != nil {
utilLogger.AppLog.Warnf("MongoDBLibrary Log level [%s] is invalid, set to [info] level",
factory.WebUIConfig.Logger.MongoDBLibrary.DebugLevel)
loggerUtil.SetLogLevel(logrus.InfoLevel)
utilLogger.SetLogLevel(zap.InfoLevel)
} else {
loggerUtil.SetLogLevel(level)
utilLogger.SetLogLevel(level)
}
} else {
loggerUtil.AppLog.Warnln("MongoDBLibrary Log level not set. Default set to [info] level")
loggerUtil.SetLogLevel(logrus.InfoLevel)
utilLogger.AppLog.Warnln("MongoDBLibrary Log level not set. Default set to [info] level")
utilLogger.SetLogLevel(zap.InfoLevel)
}
loggerUtil.SetReportCaller(factory.WebUIConfig.Logger.MongoDBLibrary.ReportCaller)
}
}

Expand Down Expand Up @@ -166,7 +148,7 @@ func (webui *WEBUI) Start() {
initLog.Infoln("WebUI Server started")

/* First HTTP Server running at port to receive Config from ROC */
subconfig_router := loggerUtil.NewGinWithLogrus(logger.GinLog)
subconfig_router := utilLogger.NewGinWithZap(logger.GinLog)
AddSwaggerUiService(subconfig_router)
AddUiService(subconfig_router)
configapi.AddServiceSub(subconfig_router)
Expand Down Expand Up @@ -237,11 +219,9 @@ func (webui *WEBUI) Start() {
}

func (webui *WEBUI) Exec(c *cli.Context) error {
// WEBUI.Initialize(cfgPath, c)

initLog.Traceln("args:", c.String("webuicfg"))
initLog.Debugln("args:", c.String("webuicfg"))
args := webui.FilterCli(c)
initLog.Traceln("filter: ", args)
initLog.Debugln("filter:", args)
command := exec.Command("./webui", args...)

webui.Initialize(c)
Expand All @@ -255,7 +235,7 @@ func (webui *WEBUI) Exec(c *cli.Context) error {
go func() {
in := bufio.NewScanner(stdout)
for in.Scan() {
fmt.Println(in.Text())
initLog.Infoln(in.Text())
}
wg.Done()
}()
Expand All @@ -267,14 +247,14 @@ func (webui *WEBUI) Exec(c *cli.Context) error {
go func() {
in := bufio.NewScanner(stderr)
for in.Scan() {
fmt.Println(in.Text())
initLog.Infoln(in.Text())
}
wg.Done()
}()

go func() {
if errCmd := command.Start(); errCmd != nil {
fmt.Println("command.Start Fails!")
initLog.Errorln("command.Start Failed")
}
wg.Done()
}()
Expand All @@ -291,7 +271,6 @@ func fetchConfigAdapater() {
(!factory.WebUIConfig.Configuration.RocEnd.Enabled) ||
(factory.WebUIConfig.Configuration.RocEnd.SyncUrl == "") {
time.Sleep(1 * time.Second)
// fmt.Printf("Continue polling config change %v ", factory.WebUIConfig.Configuration)
continue
}

Expand All @@ -300,23 +279,23 @@ func fetchConfigAdapater() {
req, err := http.NewRequest(http.MethodPost, httpend, nil)
// Handle Error
if err != nil {
fmt.Printf("An Error Occurred %v\n", err)
initLog.Errorf("an error occurred %v", err)
time.Sleep(1 * time.Second)
continue
}
// set the request header Content-Type for json
req.Header.Set("Content-Type", "application/json; charset=utf-8")
resp, err := client.Do(req)
if err != nil {
fmt.Printf("An Error Occurred %v\n", err)
initLog.Errorf("an error occurred %v", err)
time.Sleep(1 * time.Second)
continue
}
err = resp.Body.Close()
if err != nil {
fmt.Printf("An Error Occurred %v\n", err)
initLog.Errorf("an error occurred %v", err)
}
fmt.Printf("Fetching config from simapp/roc. Response code = %d \n", resp.StatusCode)
initLog.Infof("fetching config from simapp/roc. Response code = %d", resp.StatusCode)
break
}
}
4 changes: 2 additions & 2 deletions configapi/api_slice_mgmt.go
Original file line number Diff line number Diff line change
Expand Up @@ -14,7 +14,7 @@ import (
"github.com/omec-project/util/httpwrapper"
"github.com/omec-project/webconsole/backend/logger"
"github.com/omec-project/webconsole/configmodels"
"github.com/sirupsen/logrus"
"go.uber.org/zap"
)

const (
Expand All @@ -25,7 +25,7 @@ const (

var configChannel chan *configmodels.ConfigMessage

var configLog *logrus.Entry
var configLog *zap.SugaredLogger

func init() {
configLog = logger.ConfigLog
Expand Down
16 changes: 8 additions & 8 deletions go.mod
Original file line number Diff line number Diff line change
Expand Up @@ -3,20 +3,19 @@ module github.com/omec-project/webconsole
go 1.21

require (
github.com/antonfisher/nested-logrus-formatter v1.3.1
github.com/gin-contrib/cors v1.7.2
github.com/gin-gonic/gin v1.10.0
github.com/mitchellh/mapstructure v1.5.0
github.com/omec-project/config5g v1.5.0
github.com/omec-project/openapi v1.3.1
github.com/omec-project/util v1.1.0
github.com/omec-project/util v1.2.1
github.com/prometheus/client_golang v1.20.4
github.com/sirupsen/logrus v1.9.3
github.com/swaggo/files v1.0.1
github.com/swaggo/gin-swagger v1.6.0
github.com/swaggo/swag v1.16.3
github.com/urfave/cli v1.22.15
go.mongodb.org/mongo-driver v1.10.1
go.mongodb.org/mongo-driver v1.17.0
go.uber.org/zap v1.27.0
google.golang.org/grpc v1.67.0
google.golang.org/protobuf v1.34.2
gopkg.in/yaml.v2 v2.4.0
Expand Down Expand Up @@ -56,7 +55,7 @@ require (
github.com/mattn/go-isatty v0.0.20 // indirect
github.com/modern-go/concurrent v0.0.0-20180306012644-bacd9c7ef1dd // indirect
github.com/modern-go/reflect2 v1.0.2 // indirect
github.com/montanaflynn/stats v0.6.6 // indirect
github.com/montanaflynn/stats v0.7.1 // indirect
github.com/munnerz/goautoneg v0.0.0-20191010083416-a7dc8b61c822 // indirect
github.com/pelletier/go-toml/v2 v2.2.2 // indirect
github.com/pkg/errors v0.9.1 // indirect
Expand All @@ -67,9 +66,10 @@ require (
github.com/twitchyliquid64/golang-asm v0.15.1 // indirect
github.com/ugorji/go/codec v1.2.12 // indirect
github.com/xdg-go/pbkdf2 v1.0.0 // indirect
github.com/xdg-go/scram v1.1.1 // indirect
github.com/xdg-go/stringprep v1.0.3 // indirect
github.com/youmark/pkcs8 v0.0.0-20201027041543-1326539a0a0a // indirect
github.com/xdg-go/scram v1.1.2 // indirect
github.com/xdg-go/stringprep v1.0.4 // indirect
github.com/youmark/pkcs8 v0.0.0-20240726163527-a2c0da244d78 // indirect
go.uber.org/multierr v1.10.0 // indirect
golang.org/x/arch v0.8.0 // indirect
golang.org/x/crypto v0.27.0 // indirect
golang.org/x/net v0.29.0 // indirect
Expand Down
Loading

0 comments on commit a52245f

Please sign in to comment.