Skip to content

Commit

Permalink
set log level using env variables
Browse files Browse the repository at this point in the history
Signed-off-by: Amruta Kale <amrutakale24.1991@gmail.com>
  • Loading branch information
kale-amruta committed Sep 27, 2021
1 parent 491f0b2 commit 6fb2d25
Show file tree
Hide file tree
Showing 2 changed files with 43 additions and 0 deletions.
19 changes: 19 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
LevelVarName = "LOG_LEVEL"
)

// OutputSink describes the current output sink.
Expand Down Expand Up @@ -121,6 +125,21 @@ func SetFormatter(format OutputFormat) {
func init() {
SetFormatter(TextFormat)
initEnvVarFields()
level, err := logrus.ParseLevel(os.Getenv(LevelVarName))

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 GetLevel() logrus.Level {
return log.GetLevel()
}

func Info() Logger {
Expand Down
24 changes: 24 additions & 0 deletions pkg/log/log_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -105,3 +105,27 @@ 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
log.SetLevel(logrus.DebugLevel)
Debug().WithContext(ctx).Print("Testing debug level")
err = json.Unmarshal(output.Bytes(), &entry)
c.Assert(err, IsNil)
c.Assert(entry, NotNil)
c.Assert(entry["msg"], Equals, "Testing debug level")

}

0 comments on commit 6fb2d25

Please sign in to comment.