Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Set log level using env variable #1105

Merged
merged 3 commits into from
Oct 4, 2021
Merged
Show file tree
Hide file tree
Changes from 2 commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
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")
}