Skip to content

Commit

Permalink
feat: add setloglevel function
Browse files Browse the repository at this point in the history
  • Loading branch information
bilalcaliskan committed Sep 29, 2022
1 parent eb8e0de commit e7c79ec
Show file tree
Hide file tree
Showing 3 changed files with 45 additions and 3 deletions.
2 changes: 1 addition & 1 deletion go.mod
Original file line number Diff line number Diff line change
Expand Up @@ -3,6 +3,7 @@ module github.com/thevpnbeast/golang-commons
go 1.19

require (
github.com/pkg/errors v0.9.1
github.com/spf13/cast v1.5.0
github.com/stretchr/testify v1.8.0
go.uber.org/zap v1.23.0
Expand All @@ -11,7 +12,6 @@ require (
require (
github.com/davecgh/go-spew v1.1.1 // indirect
github.com/google/go-cmp v0.5.8 // indirect
github.com/pkg/errors v0.9.1 // indirect
github.com/pmezard/go-difflib v1.0.0 // indirect
go.uber.org/atomic v1.10.0 // indirect
go.uber.org/multierr v1.8.0 // indirect
Expand Down
26 changes: 24 additions & 2 deletions logging.go
Original file line number Diff line number Diff line change
Expand Up @@ -3,13 +3,20 @@ package commons
import (
"os"

"github.com/pkg/errors"

"go.uber.org/zap"
"go.uber.org/zap/zapcore"
)

var logger *zap.Logger
var (
logger *zap.Logger
atomic zap.AtomicLevel
)

func init() {
atomic = zap.NewAtomicLevel()
atomic.SetLevel(zap.InfoLevel)
logger = zap.New(zapcore.NewTee(zapcore.NewCore(zapcore.NewJSONEncoder(zapcore.EncoderConfig{
MessageKey: "message",
LevelKey: "severity",
Expand All @@ -18,10 +25,25 @@ func init() {
EncodeTime: zapcore.RFC3339TimeEncoder,
CallerKey: "caller",
EncodeCaller: zapcore.FullCallerEncoder,
}), zapcore.Lock(os.Stdout), zap.InfoLevel)))
}), zapcore.Lock(os.Stdout), atomic)))
}

// GetLogger returns the shared *VpnbeastLogger
func GetLogger() *zap.Logger {
return logger
}

// SetLogLevel function sets the log level of the *zap.Logger using zap.AtomicLevel dynamically
func SetLogLevel(level string) (*zap.Logger, error) {
if logger != nil {
parsedLevel, err := zapcore.ParseLevel(level)
if err != nil {
return nil, err
}

atomic.SetLevel(parsedLevel)
return logger, nil
}

return nil, errors.New("logger not initialized yet")
}
20 changes: 20 additions & 0 deletions logging_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -13,3 +13,23 @@ func TestGetLogger(t *testing.T) {
t.Log("will try logger for debugging")
logger.Info("test log written by zap.Logger")
}

func TestSetLogLevel(t *testing.T) {
logger, err := SetLogLevel("debug")
logger.Debug("here is the sample log written with debug level")
assert.NotNil(t, logger)
assert.Nil(t, err)
}

func TestSetLogLevelInvalidLevel(t *testing.T) {
logger, err := SetLogLevel("debugggg")
assert.Nil(t, logger)
assert.NotNil(t, err)
}

func TestSetLogLevelNotInitialized(t *testing.T) {
logger = nil
logger, err := SetLogLevel("adsfadsfadsf")
assert.Nil(t, logger)
assert.NotNil(t, err)
}

0 comments on commit e7c79ec

Please sign in to comment.