Skip to content

Commit

Permalink
Update logger to facilitate the use of global logger
Browse files Browse the repository at this point in the history
  • Loading branch information
rawmind0 committed Oct 29, 2024
1 parent f58f9e8 commit fb56921
Show file tree
Hide file tree
Showing 9 changed files with 173 additions and 71 deletions.
6 changes: 6 additions & 0 deletions Makefile
Original file line number Diff line number Diff line change
Expand Up @@ -47,6 +47,12 @@ check-modtidy:
go mod tidy
git diff --exit-code -- go.mod go.sum

fmt:
gofmt -l -s -w .

vet:
go vet ./...

lint:
golangci-lint --version
golangci-lint run
Expand Down
1 change: 1 addition & 0 deletions cmd/demo-cli/main.go
Original file line number Diff line number Diff line change
Expand Up @@ -13,6 +13,7 @@ func main() {
EnvPrefix: "golem",
GitVersion: version.GitVersion,
GitRevision: version.GitRevision,
LogLevel: "debug"

Check failure on line 16 in cmd/demo-cli/main.go

View workflow job for this annotation

GitHub Actions / checks

syntax error: unexpected newline in composite literal; possibly missing comma or }
}

// Define application level features
Expand Down
7 changes: 3 additions & 4 deletions pkg/cli/config.go
Original file line number Diff line number Diff line change
@@ -1,7 +1,6 @@
package cli

import (
"context"
"fmt"
"github.com/zondax/golem/pkg/logger"
"strings"
Expand All @@ -15,7 +14,7 @@ func SetupConfiguration(c *cobra.Command) {
c.PersistentFlags().StringVarP(&configFileFlag, "config", "c", "", "The path to the config file to use.")
err := viper.BindPFlag("config", c.PersistentFlags().Lookup("config"))
if err != nil {
logger.GetLoggerFromContext(context.Background()).Fatalf("unable to bind config flag: %+v", err)
logger.Fatalf("unable to bind config flag: %+v", err)
}

viper.SetConfigName("config") // config file name without extension
Expand Down Expand Up @@ -50,12 +49,12 @@ func LoadConfig[T Config]() (*T, error) {
configFileOverride := viper.GetString("config")
if configFileOverride != "" {
viper.SetConfigFile(configFileOverride)
logger.GetLoggerFromContext(context.Background()).Infof("Using config file: %s", viper.ConfigFileUsed())
logger.Infof("Using config file: %s", viper.ConfigFileUsed())
}

err = viper.ReadInConfig()
if err != nil {
logger.GetLoggerFromContext(context.Background()).Fatalf("%+v", err)
logger.Fatalf("%+v", err)
}

// adds all default+configFile values in viper to struct
Expand Down
8 changes: 4 additions & 4 deletions pkg/cli/handlers.go
Original file line number Diff line number Diff line change
@@ -1,11 +1,11 @@
package cli

import (
"context"
"github.com/zondax/golem/pkg/logger"
"os"
"os/signal"
"syscall"

"github.com/zondax/golem/pkg/logger"
)

var defaultConfigHandler DefaultConfigHandler
Expand All @@ -15,13 +15,13 @@ func setupCloseHandler(handler CleanUpHandler) {
signal.Notify(c, os.Interrupt, syscall.SIGTERM)
go func() {
<-c
logger.GetLoggerFromContext(context.Background()).Warn("\r- Ctrl+C pressed in Terminal")
logger.Warn("\r- Ctrl+C pressed in Terminal")

if handler != nil {
handler()
}

_ = logger.Sync() // Sync logger
logger.Sync() // Sync logger
// TODO: friendly closing callback
os.Exit(0)
}()
Expand Down
27 changes: 14 additions & 13 deletions pkg/cli/root.go
Original file line number Diff line number Diff line change
Expand Up @@ -2,11 +2,11 @@ package cli

import (
"fmt"
"os"

"github.com/spf13/cobra"
"github.com/spf13/viper"
"github.com/zondax/golem/pkg/constants"
"github.com/zondax/golem/pkg/logger"
"os"
)

type AppSettings struct {
Expand All @@ -16,6 +16,7 @@ type AppSettings struct {
EnvPrefix string // environment variable MYAPP_.....
GitVersion string
GitRevision string
LogLevel string // Global log level for the app
}

type CLI struct {
Expand Down Expand Up @@ -50,9 +51,9 @@ func (c *CLI) init() {
Run: func(cmd *cobra.Command, args []string) {
err := c.checkConfig()
if err != nil {
fmt.Printf("%s\n", c.checkConfig().Error())
logger.Errorf("%s\n", c.checkConfig().Error())
} else {
fmt.Printf("Configuration OK\n")
logger.Infof("Configuration OK\n")
}
},
}
Expand All @@ -61,15 +62,18 @@ func (c *CLI) init() {
Use: "version",
Short: "Print version",
Run: func(cmd *cobra.Command, args []string) {
fmt.Printf("%s\n", c.GetVersionString())
logger.Infof("%s\n", c.GetVersionString())
},
}

c.GetRoot().AddCommand(checkCmd)
c.GetRoot().AddCommand(versionCmd)

// TODO: We can make this optional? and more configurable if we see the need
logger.InitLogger(logger.Config{Level: constants.DebugLevel})
// If app log level is defined it is configued, logger.defaultConfig by default
if len(c.app.LogLevel) > 0 {
logger.InitLogger(logger.Config{Level: c.app.LogLevel})
}

setupCloseHandler(nil)
// Set Configuration Defaults
setupDefaultConfiguration(func() {
Expand All @@ -91,15 +95,12 @@ func (c *CLI) GetVersionString() string {

func (c *CLI) Run() {
if err := c.rootCmd.Execute(); err != nil {
_, err := fmt.Fprintln(os.Stderr, err)
if err != nil {
return
}
_ = logger.Sync()
logger.Error(err.Error())
logger.Sync()
os.Exit(1)
}
}

func (c *CLI) Close() {
_ = logger.Sync()
logger.Sync()
}
40 changes: 40 additions & 0 deletions pkg/logger/README.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,40 @@
# logger package

The logger package is intended to make unified log management in the whole app

The log may be used in 2 ways:

- Global: easy use of the global logger without the need to init or configure.
```
package main
import (
"github.com/zondax/golem/pkg/logger"
)
func main() {
// Importing logger global logger is configured in info level and may be used
logger.Info("Log info message")
// Reconfigure global logger with config
logger.SetGlobalConfig(logger.Config{Level: "debug"})
logger.Info("Log debug message")
logger.Sync()
}
```

- Local: use distinct logger for the package
```
package main
import (
"github.com/zondax/golem/pkg/logger"
)
func main() {
// Generate new logger with options and use it
log := logger.NewLogger(opts ...interface{})
log.Info("Log info message")
log.Sync()
}
```
88 changes: 88 additions & 0 deletions pkg/logger/global.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,88 @@
package logger

import (
"go.uber.org/zap"
)

func ReplaceGlobals(logger *zap.Logger) func() {
return zap.ReplaceGlobals(logger)
}

func SetGlobalConfig(config Config) func() {
logger := configureAndBuildLogger(config)
return ReplaceGlobals(logger)
}

func L() *zap.Logger {
return zap.L()
}

func S() *zap.SugaredLogger {
return zap.S()
}

func Info(msg string) {
L().Info(msg)
}

func Debug(msg string) {
L().Debug(msg)
}

func Warn(msg string) {
L().Warn(msg)
}

func Error(msg string) {
L().Error(msg)
}

func DPanic(msg string) {
L().DPanic(msg)
}

func Panic(msg string) {
L().Panic(msg)
}

func Fatal(msg string) {
L().Fatal(msg)
}

func Infof(template string, args ...interface{}) {
S().Infof(template, args...)
}

func Debugf(template string, args ...interface{}) {
S().Debugf(template, args...)
}

func Warnf(template string, args ...interface{}) {
S().Warnf(template, args...)
}

func Errorf(template string, args ...interface{}) {
S().Errorf(template, args...)
}

func DPanicf(template string, args ...interface{}) {
S().DPanicf(template, args...)
}

func Panicf(template string, args ...interface{}) {
S().Panicf(template, args...)
}

func Fatalf(template string, args ...interface{}) {
S().Fatalf(template, args...)
}

func Sync() error {
// Sync global logger
err := L().Sync()
if err != nil {
return err
}
// Sync global sugar logger
return S().Sync()
}
Loading

0 comments on commit fb56921

Please sign in to comment.