Skip to content

Commit

Permalink
Set log level using env variable (#1105)
Browse files Browse the repository at this point in the history
* set log level using env variables

Signed-off-by: Amruta Kale <amrutakale24.1991@gmail.com>

* addressed review comments

Signed-off-by: Amruta Kale <amrutakale24.1991@gmail.com>

Co-authored-by: mergify[bot] <37929162+mergify[bot]@users.noreply.github.com>
  • Loading branch information
kale-amruta and mergify[bot] committed Oct 4, 2021
1 parent 74bf729 commit a4f8a4b
Show file tree
Hide file tree
Showing 2 changed files with 44 additions and 0 deletions.
18 changes: 18 additions & 0 deletions pkg/log/log.go
Original file line number Diff line number Diff line change
Expand Up @@ -25,6 +25,10 @@ const (
InfoLevel Level = Level(logrus.InfoLevel)
// ErrorLevel log level.
ErrorLevel Level = Level(logrus.ErrorLevel)

// LevelVarName is the environment variable that controls
// init log levels
LevelEnvName = "LOG_LEVEL"
)

// OutputSink describes the current output sink.
Expand Down Expand Up @@ -121,6 +125,20 @@ func SetFormatter(format OutputFormat) {
func init() {
SetFormatter(TextFormat)
initEnvVarFields()
initLogLevel()
}

func initLogLevel() {
level, err := logrus.ParseLevel(os.Getenv(LevelEnvName))
if err != nil {
level = logrus.InfoLevel
}
SetLevel(Level(level))
}

// SetLevel sets the current log level.
func SetLevel(level Level) {
log.SetLevel(logrus.Level(level))
}

func Info() Logger {
Expand Down
26 changes: 26 additions & 0 deletions pkg/log/log_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -5,6 +5,7 @@ import (
"context"
"encoding/json"
"errors"
"os"
"testing"
"time"

Expand Down Expand Up @@ -105,3 +106,28 @@ func testLogMessage(c *C, msg string, print func(string, ...field.M), fields ...
c.Assert(entry["msg"], Equals, msg)
return entry
}

func (s *LogSuite) TestLogLevel(c *C) {
log.SetFormatter(&logrus.JSONFormatter{TimestampFormat: time.RFC3339Nano})

var output bytes.Buffer
log.SetOutput(&output)
ctx := field.Context(context.Background(), "key", "value")
var entry map[string]interface{}
//Check if debug level log is printed when log level is info
Debug().WithContext(ctx).Print("Testing debug level")
err := json.Unmarshal(output.Bytes(), &entry)

c.Assert(err, NotNil)
c.Assert(output.String(), HasLen, 0)

//Check if debug level log is printed when log level is debug
os.Setenv("LOG_LEVEL", "debug")
defer os.Unsetenv("LOG_LEVEL")
initLogLevel()
Debug().WithContext(ctx).Print("Testing debug level")
cerr := json.Unmarshal(output.Bytes(), &entry)
c.Assert(cerr, IsNil)
c.Assert(entry, NotNil)
c.Assert(entry["msg"], Equals, "Testing debug level")
}

0 comments on commit a4f8a4b

Please sign in to comment.